I'm learning golang and tried to implement a custom mix to get familiar with the language, unfortunately req.Form
is returning nil
.
Of course I'm running before req.ParseForm()
.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
params := req.Form
node, _ := r.tree.findNode(strings.Split(req.URL.Path, "/")[1:], params)
if handler := node.methods[req.Method]; handler != nil {
handler(w, req, params)
}
}
This is the example URL I'm using via GET http://localhost:8080/users/3
According to the documentation, req.Form
should always be updated if you call req.ParseForm
.
For all requests, ParseForm parses the raw query from the URL and updates r.Form.
Moreover, if you take a look at the implementation of ParseForm, it does not seem to be possible for it to be nil
after the method is executed.
https://github.com/golang/go/blob/master/src/net/http/request.go#L1238
What can indeed happen is that req.Form
ends up being an empty map, perhaps that's what you are seeing there.
It makes sense for it to be empty if you are doing:
GET http://localhost:8080/users/3
Since that has no params for ParseForm
to actually parse, so req.Form
will end up being an empty map.
If you try this for example:
GET http://localhost:8080/users/3?a=b
Then you should get an entry in the map with "a"
as a key and ["b"]
as the value.