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 镍氢电池充电器设计实物使用原理
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号