服务器认为所有请求都有r.Method“GET”

时间:2018-03-15 13:18:34

标签: http go

编辑:解决了!服务器从/ whales重定向到/ whales /,它将请求转换为GET。我的curl命令有尾部斜杠,但我的表单和Postman请求没有。

我的基本服务器总是将“GET”作为r.Method,即使是来自Postman和html表单的帖子请求也是如此。 r.Form总是一张空地图。

我的代码:

func whaleHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Print(r.Method)
    fmt.Print(r.Form)
}

func main() {
    http.HandleFunc("/whales/", whaleHandler)

    log.Fatal(http.ListenAndServe(":9002", nil))
}

这打印:

GETmap[]

我在这里做错了什么?所有人都提前致谢!

编辑:所有内容都与curl一样正常工作,但Postman和常规表单仍然被视为GET请求。

curl -d "Name=Barry" -X POST http://localhost:9002/whales/

结果:

POSTmap[]

r.FormValue("Name")吐出Barry

样本表格:

<form action="/whales" method="POST">
<div><input type="text" name="Name" placeholder="Name"></div>
<div><input type="text" name="Length" placeholder="Length"></div>
<div><input type="text" name="Type" placeholder="Type"></div>
<div><input type="submit" value="Save"></div>
</form>

来自fmt.Print(r)的完整输出,格式化了一点以便于阅读:

&{GET 
/whales/ 
HTTP/1.1 
1 
1 
map[
  Accept:[
    text/html,
    application/xhtml+xml,
    application/xml;q=0.9,*\/*;q=0.8
  ] 
  Accept-Language:[en-US,en;q=0.5] 
  Accept-Encoding:[gzip, deflate] 
  Cookie:[io=08-aNjAMs8v6ntatAAAA] 
  Connection:[keep-alive] 
  Upgrade-Insecure-Requests:[1] 
  User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:58.0) Gecko/20100101 Firefox/58.0] Referer:[http://localhost:9002/whales/create]
] 
{} 
<nil> 
0 
[] 
false 
localhost:9002 
map[] 
map[] 
<nil> 
map[] 
[::1]:61037 
/whales/ 
<nil> 
<nil> 
<nil> 
0xc420162400}

编辑: 样本邮递员请求,导致r.Method =&gt; “得到” Posting with Postman

2 个答案:

答案 0 :(得分:2)

您在&#34; / whales /&#34;下注册了您的处理程序,但您的表单操作是&#34; / whales&#34; (没有斜杠)。 Go会将请求从/ whales重定向到/ whales /在此配置中 - 大多数客户选择通过GET请求进行跟踪。

注册&#34; / whales&#34;的处理程序,或将表单操作更改为&#34; / whales /&#34;,具体取决于您希望处理的其他URL。例如,如果你需要处理/ whales / willy,请按原样保留处理程序并更改表单操作。

答案 1 :(得分:0)

您需要调用Request.ParseForm()(或间接调用它的内容,例如Request.FormValue()),直到那时Request.Form不包含表单数据。请参阅可能的重复Getting No data received for go language form

这在Request.Form

中有记录
// Form contains the parsed form data, including both the URL
// field's query parameters and the POST or PUT form data.
// This field is only available after ParseForm is called.
// The HTTP client ignores Form and uses Body instead.
Form url.Values

如果您将处理程序更改为:

func whaleHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.Method)
    fmt.Println(r.Form)
    if err := r.ParseForm(); err != nil {
        fmt.Println("Error parsing form:", err)
    }
    fmt.Println(r.Form)
}

执行curl命令:

curl -d "Name=Barry" -X POST http://localhost:9002/whales/

输出将是:

POST
map[]
map[Name:[Barry]]
相关问题