lcowell
(Luke Cowell)
December 12, 2015, 6:13pm
1
I was looking at gorilla/schema and I was wondering if there was something similar that can parse rails style params.
eg gorilla/schema can parse
user.1.phone
user.2.phone
user.1.email
user.2.email
user.first_name
user.last_name
I need something that can parse
user[]phone
user[]phone
user[]email
user[]email
user[first_name]
user[last_name]
Does such a thing exist or is this something I’ll need to write myself?
edit: added more examples
Parsing is done by stdlib net/http: call req.ParseForm.
Then you’ll have all values in req.PostForm in net/url.Values (which is a map of names and array of values for duplicated names).
If you need to rearrange them, do it yourself, but given the format you described, I think you don’t even need to.
lcowell
(Luke Cowell)
December 15, 2015, 6:02am
3
Thanks for the response. I’m thinking more about parsing those form variable names and values in to some data structure. Unless I’m overlooked something I don’t think that req.ParseForm does that. Any other ideas?
nerdyworm
(Benjamin Rhodes)
December 17, 2015, 3:27pm
4
Given the following form element:
<input type="text" name="user[name]" value="bob">
Rails would turn that into:
params // { user: { name: "bob" } }
Go would turn that into
request.FormValue("user[name]") // "bob"
Besides gorilla/schema I have not seen a lib that handles this kind of data transformation automagically.
It’s completely possible, however you will have to roll this yourself. Sorry
Another option would be to submit the form as a json so you could declare the shape of the request:
type UserParams struct {
User struct {
Name string
}
}
// in http handler
json.NewDecoder(request.Body).Decode(¶ms)
params.User.Name // bob
That may not be an option for you, but just throwing it out there.
Cheers
Ben
1 Like
lcowell
(Luke Cowell)
December 17, 2015, 5:23pm
5
Thanks for the detailed response. I may look at updating/forking scheme to handle rails style params. The json suggestion is a good one too and it’s what I have done for now.
system
(system)
Closed
March 16, 2016, 5:23pm
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.