dongtidai6519 2018-07-31 16:50
浏览 137


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

  <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=""/><br/>
    <input type="submit" value="Submit"/>

Then, I have this router in golang:

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

And this handler in golang:

func SubscribeHandler(w http.ResponseWriter, r *http.Request) {

But the problem is, it always print GET.

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


  • 写回答

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:

    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">
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



    • ¥100 webapi的部署(标签-服务器)
    • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
    • ¥15 C语言除0问题的检测方法
    • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
    • ¥15 macos13下 ios交叉编译的问题
    • ¥15 bgz压缩文件怎么打开
    • ¥15 封装dll(引入了pcl的点云设计库)
    • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发
    • ¥15 oracle 多个括号,怎么删除指定的括号及里面的内容?
    • ¥15 小新14API2019想用bios调风扇