Created
December 29, 2020 14:35
-
-
Save yrong/fdfab6dd6417c989e946d9f5842a1ab2 to your computer and use it in GitHub Desktop.
reflect by Tag
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
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