【问题标题】:Ho to bind to slice values in go (gin) form?如何绑定到 go (gin) 形式的切片值?
【发布时间】:2017-02-05 18:27:27
【问题描述】:

使用 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

quote details 产生类似:

{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"`

}

所以标签值被接收但没有被绑定。 我很想知道如何解决这个问题并从表单中获取标签? 我查看了杜松子酒guid,但找不到任何关于这种形式的信息。

【问题讨论】:

    标签: go mgo go-gin


    【解决方案1】:

    问题出在模型结构中。 我忘记在模型中添加form:"tag"。所以标签没有绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 2015-05-21
      • 2021-04-29
      • 2021-11-06
      • 2011-11-10
      • 2019-12-22
      • 2019-04-21
      • 1970-01-01
      相关资源
      最近更新 更多