Skip to content

Instantly share code, notes, and snippets.

@tonyhb
Created June 20, 2013 00:19
Show Gist options
  • Save tonyhb/5819315 to your computer and use it in GitHub Desktop.
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)
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
}
@sirdlx
Copy link

sirdlx commented May 12, 2014

Thanks, I was having a tough time rewriting code to get this working. This code works great.

@jostyee
Copy link

jostyee commented May 21, 2015

This func cannot deal with embedded structs.

@kcasas
Copy link

kcasas commented Oct 19, 2018

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
}

@ashkan90
Copy link

ashkan90 commented Aug 12, 2019

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])
}

@dreamlu
Copy link

dreamlu commented Nov 16, 2020

更一步简化完善:

// 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
}

参考:
https://github.com/dreamlu/gt/blob/2c0230b701fdbec64113111b4c651d0f6e41b040/tool/type/cmap/cmap.go#L107

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment