github.com/searKing/golang/go@v1.2.117/reflect/sub_struct_tag.go (about) 1 package reflect 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 // SubStructTag defines a single struct's string literal tag 9 type SubStructTag struct { 10 // Key is the tag key, such as json, xml, etc. 11 // i.e: `json:"foo,omitempty". Here key is: "json" 12 Key string 13 14 // Name is a part of the value 15 // i.e: `json:"foo,omitempty". Here name is: "foo" 16 Name string 17 18 // Options is a part of the value. It contains a slice of tag options i.e: 19 // `json:"foo,omitempty". Here options is: ["omitempty"] 20 Options []string 21 } 22 23 // HasOption returns true if the given option is available in options 24 func (t *SubStructTag) HasOption(opt string) bool { 25 return hasOption(t.Options, opt) 26 } 27 28 // AddOptions adds the given option. 29 // It ignores any duplicated option. 30 func (t *SubStructTag) AddOptions(opts ...string) { 31 for _, opt := range opts { 32 if t.HasOption(opt) { 33 continue 34 } 35 t.Options = append(t.Options, opt) 36 } 37 38 return 39 } 40 41 // DeleteOptions removes the given option. 42 // It ignores any option not found. 43 func (t *SubStructTag) DeleteOptions(opts ...string) { 44 var cleanOpts []string 45 for _, opt := range t.Options { 46 if hasOption(opts, opt) { 47 continue 48 } 49 cleanOpts = append(cleanOpts, opt) 50 } 51 52 t.Options = cleanOpts 53 return 54 } 55 56 // Value returns the raw value of the tag, i.e. if the tag is 57 // `json:"foo,omitempty", the Value is "foo,omitempty" 58 func (t *SubStructTag) Value() string { 59 options := strings.Join(t.Options, ",") 60 if options != "" { 61 return fmt.Sprintf(`%s,%s`, t.Name, options) 62 } 63 return t.Name 64 } 65 66 // String reassembles the tag into a valid tag field representation 67 func (t *SubStructTag) String() string { 68 return fmt.Sprintf(`%s:%q`, t.Key, t.Value()) 69 } 70 71 // GoString implements the fmt.GoStringer interface 72 func (t *SubStructTag) GoString() string { 73 return fmt.Sprintf(`{ 74 Key: '%s', 75 Name: '%s', 76 Option: '%s', 77 }`, t.Key, t.Name, strings.Join(t.Options, ",")) 78 } 79 80 func hasOption(options []string, opt string) bool { 81 for _, tagOpt := range options { 82 if tagOpt == opt { 83 return true 84 } 85 } 86 return false 87 }