编辑:解决了!服务器正在从/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}
编辑: 示例 Postman 请求,结果为 r.Method => "GET" Posting with Postman
最佳答案
您在“/whales/”下注册了您的处理程序,但您的表单操作是“/whales”(没有尾部斜线)。在此配置中,Go 会将请求从/whales 重定向到/whales/——大多数客户端选择通过 GET 请求进行跟进。
要么注册“/whales”的处理程序,要么将表单操作更改为“/whales/”,具体取决于您希望处理的其他 URL。例如,如果您需要处理/whales/willy,请保持处理程序不变并更改表单操作。
关于http - 服务器认为所有请求都有 r.Method "GET",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49300520/