Assigning FormValue to a struct

309 views
Skip to first unread message

Jaybill McCarthy

unread,
Jul 18, 2012, 2:28:05 PM7/18/12
to golan...@googlegroups.com
Before I write something, (I've searched the docs and the mailing list and can't find what I'm looking for...) is there an easy way to do marshaling with straight FormValue(s) and a struct the way you'd do with JSON?

So instead of doing this:

type User struct {
FullName string
Username string
}

u := User {FullName: r.FormValue("full_name"), Username: r.FormValue("username")}

I want to do something like this:

type User struct {
FullName string
Username string
}

u := User{}
err = form.Unmarshal(r,u)

Is there anything that does something along this line?

Peter

unread,
Jul 18, 2012, 2:56:07 PM7/18/12
to golan...@googlegroups.com
I imagine the reflect package is what you're looking for. The Request.Form is a map[string][]string, so you could loop over the keys, testing if u has a field with the same name as the key and setting the values if so. That's pretty much how the JSON unmarshaller does it, but since it takes a []byte I'm not sure if you can reuse any of it.
Message has been deleted

Jaybill McCarthy

unread,
Jul 18, 2012, 4:17:25 PM7/18/12
to Peter Russell, golan...@googlegroups.com
Yesssss.....that's exactly what I needed. Thanks!

On Wed, Jul 18, 2012 at 1:14 PM, Peter Russell <retep....@ymail.com> wrote:
Is there anything that does something along this line?


Reply all
Reply to author
Forward
0 new messages