Go 在Gin中获取PostHTML表单的所有内容

Go 在Gin中获取PostHTML表单的所有内容,go,go-gin,Go,Go Gin,我有一个HTML表单: <body> <div> <form method="POST" action="/add"name="submitForm"> <label>Message</label><input type="text" name="message" value="" />

我有一个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>
我尝试了
fmt.Println(c.PostForm(“submitForm”)
,但没有成功

我想同时访问这两个值

您可以通过从Gin上下文访问HTTP请求来实现这一点:

var vals url.Values
vals = c.Request.PostForm
请注意,
http.Request.PostForm
是一个字段。要填充它,如果您直接访问
请求
,则必须首先调用
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)
}


嗨,我知道我的答案有点晚了,好吧,快两年了,但我想贴出来供参考。顺便问一下,你是如何解决你的问题的?
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)
}