首页 > 解决方案 > 获取 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"))了,但没有奏效。

标签: gogo-gin

解决方案


我想同时访问这两个值

您可以通过从 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)
}


推荐阅读