go - 获取 Gin 中 POST HTML 表单的所有内容
问题描述
我有一个 HTML 表单:
<body>
<div>
<form method="POST" action="/add"name="submitForm">
<label>Message</label><input type="text" name="message" value="" />
<input type="checkbox" name="complete" value=""> Complete<br>
<input type="submit" value="submit" />
</form>
</div>
</body>
现在我想在 POST 发生时同时访问这两个值(消息和完成)。
我如何在 Go (gin gonic) 中做到这一点?
我可以通过使用两次来完成,c.PostForm
但有没有办法同时收集它们?:
func AddTodoHandler(c *gin.Context) {
fmt.Println(c.PostForm("message"))
fmt.Println(c.PostForm("complete"))
我试过fmt.Println(c.PostForm("submitForm"))
了,但没有奏效。
解决方案
我想同时访问这两个值
您可以通过从 Gin 上下文访问 HTTP 请求来做到这一点:
var vals url.Values
vals = c.Request.PostForm
请注意,这http.Request.PostForm
是一个字段。要填充它,如果您Request
直接访问,则必须先调用Request.ParseForm()
。
作为替代方案,您可以使用 Gin 绑定来填充结构并从中访问相关字段:
type MyForm struct {
Message string `form:"message"`
Complete bool `form:"complete"`
}
func AddTodoHandler(c *gin.Context) {
form := &MyForm{}
if err := c.ShouldBind(form); err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
fmt.Println(form.Message)
fmt.Println(form.Complete)
}
推荐阅读
- php - Pre_replace 用正则表达式替换域和电子邮件的字符串
- java - 如何使用领域保存模型数据?
- php - 每个问题有多个正确答案的测验
- jquery - 通过鼠标悬停隐藏和显示不起作用。知道为什么我的代码不起作用吗?
- java - 将字符串写入文件时如何换行?
- c# - 如何在 c# 中的 Datetime 属性中添加几天?
- javascript - 来自 CSV 文件数据的样条被渲染太多次
- javascript - 如何使用映射过滤嵌套数组并使用对象过滤
- c# - 使用 C# 将数据插入 SQL Server
- tensorflow - 在 Keras/Tensorflow 中实现自定义 WARP 损失函数时出现错误:LookupError: No gradient defined for operation