Skip to content

Instantly share code, notes, and snippets.

@unsafe9
Created November 3, 2020 09:43
Show Gist options
  • Save unsafe9/72a44c88a9b594fe441f0c801ce391b2 to your computer and use it in GitHub Desktop.
Save unsafe9/72a44c88a9b594fe441f0c801ce391b2 to your computer and use it in GitHub Desktop.
package util
import (
"reflect"
"strings"
)
var fieldNamesByTag = make(map[reflect.Type]map[string]map[string]string)
func BuildFieldsByTagMap(s interface{}, key string) {
rt := reflect.TypeOf(s)
if rt.Kind() != reflect.Struct {
panic("bad type")
}
if fieldNamesByTag[rt] == nil {
fieldNamesByTag[rt] = make(map[string]map[string]string)
}
if fieldNamesByTag[rt][key] == nil {
fieldNamesByTag[rt][key] = make(map[string]string)
}
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
// use split to ignore tag "options"
tag := strings.Split(field.Tag.Get(key), ",")[0]
if tag == "" || tag == "-" {
continue
}
fieldNamesByTag[rt][key][tag] = field.Name
}
}
func FieldValueByName(s interface{}, key, tag string) interface{} {
rt := reflect.TypeOf(s)
// panic wrong call
if rt.Kind() != reflect.Struct {
panic("bad type")
} else if tag == "" || tag == "-" {
panic("bad parameter")
}
if typeMap, exists := fieldNamesByTag[rt]; !exists {
panic("bad type")
} else if keyMap, exists := typeMap[key]; !exists {
panic("bad key")
} else if fieldName, exists := keyMap[tag]; !exists {
panic("bad tag")
} else {
return reflect.ValueOf(s).FieldByName(fieldName).Interface()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment