1package types 2 3import ( 4 "fmt" 5 "reflect" 6 "strings" 7) 8 9// EnumParser parses "enum" values; i.e. a predefined set of strings to 10// predefined values. 11type EnumParser struct { 12 Type string // type name; if not set, use type of first value added 13 CaseMatch bool // if true, matching of strings is case-sensitive 14 // PrefixMatch bool 15 vals map[string]interface{} 16} 17 18// AddVals adds strings and values to an EnumParser. 19func (ep *EnumParser) AddVals(vals map[string]interface{}) { 20 if ep.vals == nil { 21 ep.vals = make(map[string]interface{}) 22 } 23 for k, v := range vals { 24 if ep.Type == "" { 25 ep.Type = reflect.TypeOf(v).Name() 26 } 27 if !ep.CaseMatch { 28 k = strings.ToLower(k) 29 } 30 ep.vals[k] = v 31 } 32} 33 34// Parse parses the string and returns the value or an error. 35func (ep EnumParser) Parse(s string) (interface{}, error) { 36 if !ep.CaseMatch { 37 s = strings.ToLower(s) 38 } 39 v, ok := ep.vals[s] 40 if !ok { 41 return false, fmt.Errorf("failed to parse %s %#q", ep.Type, s) 42 } 43 return v, nil 44} 45