douxu2081 2016-09-28 00:25
浏览 189

如何以go(gin)形式绑定到slice值?

Using go and gin-gonic, I'd like to post a simple form containing two tag fields and then save it to mongodb.

Here is the form:

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

And the handler is:

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
")
    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")
}

Now the problem is as for form post values I get:

0 mytag1
1 mytag2

and quote details yields something like:

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

The quote model is like this:

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

}

So the tag values are received but not binded. I'm wondeirng how can I fix this and get the tags from the form? I've looked at the gin guid but could not find anything about this sort of forms.

  • 写回答

1条回答 默认 最新

  • douchi0638 2016-09-28 03:35
    关注

    The problem was in the model struct. I forgot to add form:"tag" to the model. So the tag did not bind.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法