doqvzh345334 2018-03-15 13: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 16: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条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题