dongtidai6519 2018-07-31 16:50
浏览 137
已采纳

带有Golang的HTML表单方法发布

So, I have this form in an html. It is intended to have a POST request to /subscribe page:

<html>
  <form action="/subscribe" method="post">
    First Name: <input type="text" name="first_name" placeholder="Willy"/><br/>
    Last Name: <input type="text" name="last_name" placeholder="Warmwood"/><br/>
    Email: <input type="email" name="email" placeholder="willy.warwood@gmail.com"/><br/>
    <input type="submit" value="Submit"/>
  </form>
</html>

Then, I have this router in golang:

http.HandleFunc("/subscribe/", SubscribeHandler)

And this handler in golang:

func SubscribeHandler(w http.ResponseWriter, r *http.Request) {
    log.Println(r.Method)
}

But the problem is, it always print GET.

How to post the form, so the value of r.Method is POST?

Thanks

  • 写回答

1条回答 默认 最新

  • duanan1228 2018-07-31 17:50
    关注

    Per the docs:

    If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash.

    Because you registered "/subscribe/", with the trailing slash, it is registered as a subtree. Again, per the docs:

    a pattern ending in a slash names a rooted subtree

    Because an HTTP redirect is (in practice) always a GET request, the method after the redirect is of course a GET. You can see that a real redirect is happening in this example: https://play.golang.org/p/OcEhVDosTNf

    The solution is to either register both:

    http.HandleFunc("/subscribe/", SubscribeHandler)
    http.HandleFunc("/subscribe", SubscribeHandler)
    

    Or point your form to the one with a /:

    <form action="/subscribe/" method="post">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记