html - 使用 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
?
谢谢
解决方案
根据文档:
如果已注册子树并且接收到命名子树根但没有尾部斜杠的请求,则 ServeMux 将该请求重定向到子树根(添加尾部斜杠)。可以通过单独注册不带斜杠的路径来覆盖此行为。
因为您注册了"/subscribe/"
,带有斜杠,所以它被注册为子树。同样,根据文档:
以斜杠结尾的模式命名有根子树
因为 HTTP 重定向(实际上)始终是 GET 请求,所以重定向之后的方法当然是 GET。您可以看到在此示例中发生了真正的重定向:https: //play.golang.org/p/OcEhVDosTNf
解决方案是注册两者:
http.HandleFunc("/subscribe/", SubscribeHandler)
http.HandleFunc("/subscribe", SubscribeHandler)
或者将您的表单指向带有以下内容的表单/
:
<form action="/subscribe/" method="post">
推荐阅读
- c# - 如何通过扩展中的 PXActions 正确地将记录添加到 DAC
- python-3.x - 如何替换字符串中的十六进制值
- c++ - 有没有办法解决这个错误:'operator[]' 不匹配(操作数类型是 'empl' 和 'int')
- c# - 在 NHibernate 查询中实现条件的更好方法是什么?
- centreon-api - 是否有可能通过 CLI 而不是通过 Web 界面进行配置来安装 Centreon?
- vba - 使用 VBA 格式化 PowerPoint 表格非常慢
- vsto - 插件无法在 Outlook 中看到
- angular - 启动画面不会隐藏在设备上的 --prod 模式中
- azure - 从追加 Blob 复制到 BlockBlob
- youtube - 有没有办法以编程方式下载 mp4 格式的 youtube 视频?