gitee.com/h79/goutils@v1.22.10/common/tag/tag.go (about) 1 package tag 2 3 import ( 4 "reflect" 5 "strings" 6 ) 7 8 func StructVal(s interface{}) reflect.Value { 9 v := reflect.ValueOf(s) 10 11 // if pointer get the underlying element≤ 12 for v.Kind() == reflect.Ptr { 13 v = v.Elem() 14 } 15 16 if v.Kind() != reflect.Struct { 17 panic("not struct") 18 } 19 20 return v 21 } 22 23 func StructFields(value reflect.Value, tagName string) []reflect.StructField { 24 t := value.Type() 25 26 var f []reflect.StructField 27 28 for i := 0; i < t.NumField(); i++ { 29 field := t.Field(i) 30 // we can't access the value of unexported fields 31 if field.PkgPath != "" { 32 continue 33 } 34 // don't check if it's omitted 35 if tag := field.Tag.Get(tagName); tag == "-" { 36 continue 37 } 38 f = append(f, field) 39 } 40 return f 41 } 42 43 // Tags contains a slice of tag options 44 type Tags []string 45 46 // Has returns true if the given option is available in Tags 47 func (t Tags) Has(opt string) bool { 48 for i := range t { 49 if t[i] == opt { 50 return true 51 } 52 } 53 return false 54 } 55 56 func Parse(tag string) (string, Tags) { 57 // tag is one of followings: 58 // "" 59 // "name" 60 // "name,opt" 61 // "name,opt,opt2" 62 // ",opt" 63 64 res := strings.Split(tag, ",") 65 return res[0], res[1:] 66 }