Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse form array in golang Beego

Tags:

html

forms

go

How to parse html form array with Beego.

<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:[]}

Why Beego ParseForm method return an empty names?

How to get values into rsvp.Names?

like image 900
Mathdoy Avatar asked May 17 '14 16:05

Mathdoy


2 Answers

Thanks @ysqi for giving me a hint. I am adding a little detailed example to parse associate array like form data in beego

Here is my form structure:

<input name="contacts[0][email]" type="text" value="[email protected]"/>
<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="[email protected]"/>
<input name="contacts[1][first_name]" type="text" value="f2"/>
<input name="contacts[1][last_name]" type="text" value="l2"/>

golang(beego) code:

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

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

contacts variable:

[
  {
    "email": "[email protected]",
    "first_name": "Sam",
    "last_name": "Gamge"
  },
  {
    "email": "[email protected]",
    "first_name": "john",
    "last_name": "doe"
  }
]

Now you can use it like:

for _, contact := range contacts {
    contact["email"]
    contact["first_name"]
    contact["last_name"]
}
like image 151
cool_php Avatar answered Sep 21 '22 01:09

cool_php


As you can see from the implementation of the FormValue method of the Request, it returns the first value in case of multiple ones: http://golang.org/src/pkg/net/http/request.go?s=23078:23124#L795 It would be better to get the attribute itself r.Form[key] and iterate over all the results manually. I am not sure how Beego works, but just using the raw Request.ParseForm and Request.Form or Request.PostForm maps should do the job. http://golang.org/src/pkg/net/http/request.go?s=1939:6442#L61

like image 40
Feras Avatar answered Sep 20 '22 01:09

Feras