首页 > 解决方案 > 使用 Golang 发布 HTML 表单方法

问题描述

所以,我在 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

谢谢

标签: htmlformsgopostmethods

解决方案


根据文档:

如果已注册子树并且接收到命名子树根但没有尾部斜杠的请求,则 ServeMux 将该请求重定向到子树根(添加尾部斜杠)。可以通过单独注册不带斜杠的路径来覆盖此行为。

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

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

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

解决方案是注册两者:

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

或者将您的表单指向带有以下内容的表单/

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

推荐阅读