带有Golang的HTML表单方法发布

时间:2018-07-31 16:50:33

标签: html forms go post methods

因此,我在html中有此表格。旨在向/subscribe页发送POST请求:

<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>

然后,我在golang中安装了该路由器:

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

还有golang中的此处理程序:

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

但是问题是,它总是打印GET

如何发布表单,因此r.Method的值为POST

谢谢

1 个答案:

答案 0 :(得分:3)

根据文档:

  

如果已经注册了一个子树,并且接收到一个命名该子树根的请求而没有其斜杠,则ServeMux将该请求重定向到子树根(添加尾斜杠)。可以用单独的路径注册来覆盖此行为,而不用斜杠结尾。

因为您用后跟斜杠注册了"/subscribe/" ,所以它被注册为子树。同样,根据文档:

  

以斜杠结尾的模式命名为根子树

由于(实际上)HTTP重定向始终是GET请求,因此重定向之后的方法当然是GET。您可以看到在此示例中发生了真正的重定向:https://play.golang.org/p/OcEhVDosTNf

解决方案是同时注册两个:

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

或将您的表单指向带有/的表单:

<form action="/subscribe/" method="post">