Created
August 16, 2016 09:11
-
-
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).
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
// 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:] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi, how to use this? is variable $in is the struck? like...
var(
in mode.user
)
??