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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示