申请表返回零

Request Form is returning nil

我正在学习 golang 并尝试实现自定义组合以熟悉该语言,不幸的是 req.Form 正在返回 nil

我当然是 运行 之前 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)
    }
}

这是示例 URL 我通过 GET http://localhost:8080/users/3

使用

根据文档,如果您调用 req.ParseForm.

req.Form 应该始终更新

For all requests, ParseForm parses the raw query from the URL and updates r.Form.

此外,如果你看一下ParseForm的实现,似乎不可能nil执行完方法后

https://github.com/golang/go/blob/master/src/net/http/request.go#L1238

确实可能发生的是 req.Form 最终变成一张空地图,也许这就是您在那里看到的。

它是空的,如果你这样做是有意义的:

GET http://localhost:8080/users/3

因为 ParseForm 没有参数来实际解析,所以 req.Form 最终将成为一个空映射。

例如,如果您尝试这样做:

GET http://localhost:8080/users/3?a=b

然后您应该在地图中获得一个条目,其中 "a" 作为键,["b"] 作为值。