Skip to content

Instantly share code, notes, and snippets.

@derlin
Created August 16, 2016 09:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derlin/0be53d0d7f38db181198aada024269b8 to your computer and use it in GitHub Desktop.
Save derlin/0be53d0d7f38db181198aada024269b8 to your computer and use it in GitHub Desktop.
Golang utility to transform a struct to a map with keys in lowercase. Useful to map struct to json (uppercase names always make me blink).
// see https://play.golang.org/p/6YD4YdvGLr
// for an example
import (
"reflect"
"unicode"
"unicode/utf8"
)
func structToLowerFirstMap(in interface{}) map[string]interface{} {
v := reflect.ValueOf(in)
vType := v.Type()
result := make(map[string]interface{}, v.NumField())
for i := 0; i < v.NumField(); i++ {
name := vType.Field(i).Name
result[lowerFirst(name)] = v.Field(i).Interface()
}
return result;
}
func lowerFirst(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
}
@jakskal
Copy link

jakskal commented Oct 8, 2018

hi, how to use this? is variable $in is the struck? like...
var(
in mode.user
)
??

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