本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
998B

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