如何在golang Beego中解析表单数组

时间:2014-05-17 16:47:10

标签: html forms go

如何使用Beego解析html表单数组。

<input name="names[]" type="text" /> <input name="names[]" type="text" /> <input name="names[]" type="text" />

Go Beego

type Rsvp struct {
    Id    int      `form:"-"`
    Names []string `form:"names[]"`
}

rsvp := Rsvp{}
if err := this.ParseForm(&rsvp); err != nil {
    //handle error
}

input := this.Input()
fmt.Printf("%+v\n", input) // map[names[]:[name1 name2 name3]]
fmt.Printf("%+v\n", rsvp) // {Names:[]}

为什么Beego ParseForm方法会返回一个空名称?

如何将值输入rsvp.Names?

3 个答案:

答案 0 :(得分:4)

从Request的FormValue方法的实现中可以看出,它返回第一个值,如果有多个: http://golang.org/src/pkg/net/http/request.go?s=23078:23124#L795 最好是获取属性本身r.Form [key]并手动迭代所有结果。我不确定Beego是如何工作的,但只是使用原始的 Request.ParseForm和Request.Form或Request.PostForm映射应该完成这项工作。 http://golang.org/src/pkg/net/http/request.go?s=1939:6442#L61

答案 1 :(得分:3)

感谢@ysqi给我一个提示。我正在添加一个详细的例子来解析关联数组,如beego中的表单数据

这是我的表单结构:

<input name="contacts[0][email]" type="text" value="a1@gmail.com"/>
<input name="contacts[0][first_name]" type="text" value="f1"/>
<input name="contacts[0][last_name]" type="text" value="l1"/>
<input name="contacts[1][email]" type="text" value="a2@gmail.com"/>
<input name="contacts[1][first_name]" type="text" value="f2"/>
<input name="contacts[1][last_name]" type="text" value="l2"/>
golang(beego)代码:

contacts := make([]map[string]string, 0, 3)

this.Ctx.Input.Bind(&contacts, "contacts")

联系人变量:

[
  {
    "email": "user2@gmail.com",
    "first_name": "Sam",
    "last_name": "Gamge"
  },
  {
    "email": "user3@gmail.com",
    "first_name": "john",
    "last_name": "doe"
  }
]

现在您可以使用它:

for _, contact := range contacts {
    contact["email"]
    contact["first_name"]
    contact["last_name"]
}

答案 2 :(得分:2)

你可以这样做:见doc

v := make([]string, 0, 3)
this.Ctx.Input.Bind(&v, "names")