doqvzh345334 2018-03-15 05:18
浏览 84
已采纳

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

Edit: solved! The server was redirecting from /whales to /whales/, which transformed the request into a GET. My curl command had the trailing slash, but my form and Postman request did not.


My basic server always has "GET" as r.Method, even for post requests from Postman and html forms. r.Form is always an empty map.

My code:

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))
}

And this prints:

GETmap[]

What am I doing wrong here? Thanks in advance, all!


Edit: everything works as expected with curl, but Postman and regular forms are still being treated like GET requests.

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

results in:

POSTmap[],

and r.FormValue("Name") spits out Barry


Sample form:

<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>

And full output from fmt.Print(r), formatted a little for readability:

&{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[] 

/whales/ 
<nil> 
<nil> 
<nil> 
0xc420162400}

Edit: Sample Postman request, which results in r.Method => "GET" Posting with Postman

展开全部

  • 写回答

2条回答 默认 最新

  • donoworuq450547191 2018-03-15 08:38
    关注

    You registered your handler under "/whales/", but your form action is "/whales" (without trailing slash). Go will redirect requests from /whales to /whales/ in this configuration -- most clients choose to follow via GET requests.

    Either register the handler for "/whales", or change the form action to "/whales/", depending on other URLs you wish to handle. E.g., if you need to handle /whales/willy, leave the handler as-is and change the form action.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部