0

I am very new to Go, infact started today. But have run into a weird and frustrating problem. Simply put, the following code prints r.Method as GET when I make a POST request via POSTMAN.

package main

import (
    "fmt"
    "net/http"
    "routes"
)

func cartHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Printf(r.Method);
    if r.Method == "GET" {
        cart.GetHandler(w,r)
    } else if r.Method == "POST" {
        cart.PostHandler(w,r)
    }
    //fmt.Fprintf(w, "Hi there, I love %s!", r.Method)
}

func main() {
    http.HandleFunc("/cart/", cartHandler)
    http.ListenAndServe(":8010", nil)
}

The request being made is fine because a similar piece of code in nodejs detects it as a POST request.

  • Thanks Riscie, curl -X POST worked for me too. But still, POSTMAN should work as well, not sure if you use it, but I find it pretty handy. – Anand Thakur Jan 29 '16 at 13:04
  • So I just tested it with POSTMAN (the chrome extension) and it detects my POSTs as POST and GETs as GET. Not sure what is going wrong there... – Riscie Jan 29 '16 at 13:05
  • 1
    I think I know whats wrong here. Did you enter the complete url into POSTMAN? including the last slash? Because if I don't enter the last slash, my POST is discovered as GET as well.... – Riscie Jan 29 '16 at 13:07
  • That was it... so frustrating, but that shouldn't have mattered right? – Anand Thakur Jan 29 '16 at 13:08
  • Well I am not quite sure what POSTMAN does but actually, the request shouldn't even get to your handlefunc. If I do the same test with curl, the request ends in the nirvana, which is what I would expect, because we don't have a route for /cart, only for /cart/ – Riscie Jan 29 '16 at 13:09
  • 1
    Ok. Anyways, thanks for figuring this out. – Anand Thakur Jan 29 '16 at 13:11
  • Btw. Here is a discussion about wether to use trailing slashes or not in URLs. Might be relevant. http://stackoverflow.com/questions/5948659/trailing-slash-in-urls-which-style-to-use – Riscie Jan 29 '16 at 13:16
  • Probably a prefetch of sorts. Like how chrome will GET `/favicon.ico` for a domain. – thwd Jan 29 '16 at 14:20
  • Could be @thwd. However it seems like not the right thing to do in a tool specially designed for testing http backends... – Riscie Jan 29 '16 at 15:26
  • fwiw: I asked about this within the POSTMAN project over at github. If someone likes to know more about why this happens... https://github.com/postmanlabs/postman-app-support/issues/1687 – Riscie Jan 30 '16 at 12:59

1 Answers1

4

In your HandleFunc remove the last trailing slash

    http.HandleFunc("/cart", cartHandler)

instead of

    http.HandleFunc("/cart/", cartHandler)

Or if you want your URL like that, enter it with the slash in POSTMAN and it should work like expected.

Riscie
  • 3,775
  • 1
  • 24
  • 31