Created
June 20, 2013 00:19
-
-
Save tonyhb/5819315 to your computer and use it in GitHub Desktop.
Golang: Converting a struct to a map (to a url.Values string map)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/url" | |
"reflect" | |
"strconv" | |
) | |
type Person struct { | |
Name string | |
Age uint | |
} | |
func main() { | |
betty := Person{ | |
Name: "Betty", | |
Age: 82, | |
} | |
urlValues := structToMap(&betty) | |
fmt.Printf("%#v", urlValues) | |
// Response... | |
// url.Values{"Name":[]string{"Betty"}, "Age":[]string{"82"}} | |
// It works! Play with it @ http://play.golang.org/p/R8jhzfI_ac | |
} | |
func structToMap(i interface{}) (values url.Values) { | |
values = url.Values{} | |
iVal := reflect.ValueOf(i).Elem() | |
typ := iVal.Type() | |
for i := 0; i < iVal.NumField(); i++ { | |
f := iVal.Field(i) | |
// You ca use tags here... | |
// tag := typ.Field(i).Tag.Get("tagname") | |
// Convert each type into a string for the url.Values string map | |
var v string | |
switch f.Interface().(type) { | |
case int, int8, int16, int32, int64: | |
v = strconv.FormatInt(f.Int(), 10) | |
case uint, uint8, uint16, uint32, uint64: | |
v = strconv.FormatUint(f.Uint(), 10) | |
case float32: | |
v = strconv.FormatFloat(f.Float(), 'f', 4, 32) | |
case float64: | |
v = strconv.FormatFloat(f.Float(), 'f', 4, 64) | |
case []byte: | |
v = string(f.Bytes()) | |
case string: | |
v = f.String() | |
} | |
values.Set(typ.Field(i).Name, v) | |
} | |
return | |
} |
This func cannot deal with embedded structs.
A shorter version would be
func structToMap(i interface{}) (values url.Values) {
values = url.Values{}
iVal := reflect.ValueOf(i).Elem()
typ := iVal.Type()
for i := 0; i < iVal.NumField(); i++ {
values.Set(typ.Field(i).Name, fmt.Sprint(iVal.Field(i)))
}
return
}
if the wish only converting interface{} (type of url.Values) to map, then we can do this;
convert url.Values to map string
func someHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
mapValOfForm := r.Form.(url.Values)
fmt.Println(mapValOfForm[formKey])
}
更一步简化完善:
// CMap = url.Values{} = map[string][]string
// struct to CMap, maybe use Encode
func StructToMap(v interface{}) (values CMap) {
values = NewCMap()
el := reflect.ValueOf(v)
if el.Kind() == reflect.Ptr {
el = el.Elem()
}
iVal := el
typ := iVal.Type()
for i := 0; i < iVal.NumField(); i++ {
fi := typ.Field(i)
name := fi.Tag.Get("json")
if name == "" {
name = fi.Name
}
values.Set(name, fmt.Sprint(iVal.Field(i)))
}
return
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, I was having a tough time rewriting code to get this working. This code works great.