github.com/jxskiss/gopkg@v0.17.3/structtag/tag_options.go (about) 1 package structtag 2 3 import "strings" 4 5 // Options represents a set of parsed options of a struct field tag. 6 type Options []Option 7 8 func (p Options) Get(option string) (Option, bool) { 9 for _, opt := range p { 10 if opt.k == option { 11 return opt, true 12 } 13 } 14 return Option{}, false 15 } 16 17 // Option represents a single option from a struct field tag. 18 type Option struct { 19 raw, k, v string 20 } 21 22 // String returns the original string represent of the option. 23 func (p Option) String() string { return p.raw } 24 25 // Key returns the parsed key of the option, if available. 26 func (p Option) Key() string { return p.k } 27 28 // Value returns the parsed value of the option, if available. 29 func (p Option) Value() string { return p.v } 30 31 // ParseOptions parses tag into Options using optionSep and kvSep. 32 // 33 // If optionSep is not empty, it splits tag into options using optionSep 34 // as separator, else the whole tag is considered as a single option. 35 // If kvSep is not empty, it splits each option into key value pair using 36 // kvSep as separator, else the option's key, value will be empty. 37 func ParseOptions(tag string, optionSep, kvSep string) Options { 38 tag = strings.TrimSpace(tag) 39 if tag == "" { 40 return nil 41 } 42 43 var options []Option 44 var opts []string 45 if optionSep == "" { 46 opts = []string{tag} 47 } else { 48 opts = strings.Split(tag, optionSep) 49 } 50 51 for _, optstr := range opts { 52 optstr = strings.TrimSpace(optstr) 53 opt := Option{raw: optstr} 54 if kvSep != "" { 55 sepIdx := strings.Index(optstr, kvSep) 56 if sepIdx < 0 { 57 opt.k = optstr 58 } else { 59 opt.k = strings.TrimSpace(optstr[:sepIdx]) 60 opt.v = strings.TrimSpace(optstr[sepIdx+1:]) 61 } 62 } 63 options = append(options, opt) 64 } 65 return options 66 }