Skip to content

Instantly share code, notes, and snippets.

@yrong
Created December 29, 2020 14:35
Show Gist options
  • Save yrong/fdfab6dd6417c989e946d9f5842a1ab2 to your computer and use it in GitHub Desktop.
Save yrong/fdfab6dd6417c989e946d9f5842a1ab2 to your computer and use it in GitHub Desktop.
reflect by Tag
package main
import (
"fmt"
"reflect"
"strings"
)
type Human struct {
Head string `json:"a1" xml:"x1"`
Body string `json:"a2" xml:"x2"`
Leg string `json:"a3,omitempty" xml:"x3"`
}
func getFieldName(tag, key string, s interface{}) (fieldname string) {
rt := reflect.TypeOf(s)
if rt.Kind() != reflect.Struct {
panic("bad type")
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
v := strings.Split(f.Tag.Get(key), ",")[0] // use split to ignore tag "options"
if v == tag {
return f.Name
}
}
return ""
}
func main() {
fmt.Println(getFieldName("a1", "json", Human{}))
fmt.Println(getFieldName("a3", "json", Human{}))
fmt.Println(getFieldName("a2", "json", Human{}))
fmt.Println(getFieldName("x2", "xml", Human{}))
fmt.Println(getFieldName("a99", "json", Human{}))
fmt.Println(getFieldName("a99", "json", "Human{}")) // panic if not struct
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment