In Go, http-form data (for example, from a POST or PUT request) can be obtained as a map of the form map[string][]string . It is difficult for me to convert this into structures in a generalized way.
For example, I want to download a map such as:
m := map[string][]string { "Age": []string{"20"}, "Name": []string{"John Smith"}, }
In a model, for example:
type Person struct { Age int Name string }
So, I'm trying to write a function with the signature LoadModel(obj interface{}, m map[string][]string) []error , which will load the form data into the interface {}, which I can print to return to the character. Using reflection, so that I can use it for any type of structure with any fields, not just Face, and so that I can convert a string from http data to int, boolean, etc. As needed.
Using the answer to this question in golang, using reflection, how do you set the value of a struct field? I can set the value of a person using reflection, for example:
p := Person{25, "John"} reflect.ValueOf(&p).Elem().Field(1).SetString("Dave")
But then I will have to copy the load function for each type of structure that I have. When I try to use it for the {} interface, it does not work.
pi := (interface{})(p) reflect.ValueOf(&pi).Elem().Field(1).SetString("Dave")
How can I do this in general? Or, better yet, is there a more idiomatic way to achieve what I'm trying to do?
danny
source share