go - 如何绑定(bind)到 go (gin) 形式的 slice 值?

标签 go mgo go-gin

使用 go 和 gin-gonic,我想发布一个包含两个标记字段的简单表单,然后将其保存到 mongodb。

这是表格:

      <form action="/quotes/{{ .quote.Id.Hex }}" method="POST">    
          <input type="text" name="author" value="{{ .quote.Author }}">     
          <textarea name="body" rows="3">{{ .quote.Body }}</textarea>       

          <input name="tag" value="" >    
          <input name="tag" value="" >      

         <button type="submit">Submit</button>
  </form>

处理程序是:

func Create(c *gin.Context) {
    db := c.MustGet("db").(*mgo.Database)
    quote := models.Quote{}
    err := c.Bind(&quote)
    if err != nil {
        c.Error(err)
        return
    }

    //To debug
    fmt.Println("form post values\n")
    for t, v := range c.Request.Form["tag"] {
      fmt.Println(t, v) 
    }

    //To debug
    fmt.Println(quote)

    err = db.C(models.CollectionQuote).Insert(quote)
    if err != nil {
        c.Error(err)
    }
    c.Redirect(http.StatusMovedPermanently, "/quotes")
}

现在的问题是关于 form post values 我得到:

0 mytag1
1 mytag2

引用细节会产生如下内容:

{ObjectIdHex("") some-author somebody [] }

报价模型是这样的:

// Quote model
type Quote struct {
    Id        bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
    Author     string        `json:"author" form:"author" binding:"required" bson:"author"`
    Body      string        `json:"body" form:"body" binding:"required" bson:"body"`
    Tag       []string      `json:"tag" bson:"tag"`

}

所以标签值被接收但没有绑定(bind)。 我想知道如何解决这个问题并从表单中获取标签? 我看过 Gin guid但找不到有关此类表格的任何信息。

最佳答案

问题出在模型结构中。 我忘了将 form:"tag" 添加到模型中。所以标签没有绑定(bind)。

关于go - 如何绑定(bind)到 go (gin) 形式的 slice 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39736243/

相关文章:

mongodb - 为什么 mgo 不能正确解码我的结构?

go - 在1页中将相同的模板与不同的参数/变量一起使用

go - Gin 和中间件

go - 如何设置CORS设置

go - go.mod上的严格版本

struct - 为什么将结构传递给当前包中带有文字结构参数的函数不同于另一个包中的函数?

mongodb - 监视 MongoDB 更改流

mongodb - 使用 mgo 从 golang 中的 Mongodb 中选择列

go - channel 结束父例程后返回

xml - Go语言中从xml中解码数组