marshaler.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package mapping
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. const (
  8. emptyTag = ""
  9. tagKVSeparator = ":"
  10. )
  11. // Marshal marshals the given val and returns the map that contains the fields.
  12. // optional=another is not implemented, and it's hard to implement and not common used.
  13. func Marshal(val any) (map[string]map[string]any, error) {
  14. ret := make(map[string]map[string]any)
  15. tp := reflect.TypeOf(val)
  16. if tp.Kind() == reflect.Ptr {
  17. tp = tp.Elem()
  18. }
  19. rv := reflect.ValueOf(val)
  20. if rv.Kind() == reflect.Ptr {
  21. rv = rv.Elem()
  22. }
  23. for i := 0; i < tp.NumField(); i++ {
  24. field := tp.Field(i)
  25. value := rv.Field(i)
  26. if err := processMember(field, value, ret); err != nil {
  27. return nil, err
  28. }
  29. }
  30. return ret, nil
  31. }
  32. func getTag(field reflect.StructField) (string, bool) {
  33. tag := string(field.Tag)
  34. if i := strings.Index(tag, tagKVSeparator); i >= 0 {
  35. return strings.TrimSpace(tag[:i]), true
  36. }
  37. return strings.TrimSpace(tag), false
  38. }
  39. func processMember(field reflect.StructField, value reflect.Value,
  40. collector map[string]map[string]any) error {
  41. var key string
  42. var opt *fieldOptions
  43. var err error
  44. tag, ok := getTag(field)
  45. if !ok {
  46. tag = emptyTag
  47. key = field.Name
  48. } else {
  49. key, opt, err = parseKeyAndOptions(tag, field)
  50. if err != nil {
  51. return err
  52. }
  53. if err = validate(field, value, opt); err != nil {
  54. return err
  55. }
  56. }
  57. val := value.Interface()
  58. if opt != nil && opt.FromString {
  59. val = fmt.Sprint(val)
  60. }
  61. m, ok := collector[tag]
  62. if ok {
  63. m[key] = val
  64. } else {
  65. m = map[string]any{
  66. key: val,
  67. }
  68. }
  69. collector[tag] = m
  70. return nil
  71. }
  72. func validate(field reflect.StructField, value reflect.Value, opt *fieldOptions) error {
  73. if opt == nil || !opt.Optional {
  74. if err := validateOptional(field, value); err != nil {
  75. return err
  76. }
  77. }
  78. if opt == nil {
  79. return nil
  80. }
  81. if opt.Optional && value.IsZero() {
  82. return nil
  83. }
  84. if len(opt.Options) > 0 {
  85. if err := validateOptions(value, opt); err != nil {
  86. return err
  87. }
  88. }
  89. if opt.Range != nil {
  90. if err := validateRange(value, opt); err != nil {
  91. return err
  92. }
  93. }
  94. return nil
  95. }
  96. func validateOptional(field reflect.StructField, value reflect.Value) error {
  97. switch field.Type.Kind() {
  98. case reflect.Ptr:
  99. if value.IsNil() {
  100. return fmt.Errorf("field %q is nil", field.Name)
  101. }
  102. case reflect.Array, reflect.Slice, reflect.Map:
  103. if value.IsNil() || value.Len() == 0 {
  104. return fmt.Errorf("field %q is empty", field.Name)
  105. }
  106. }
  107. return nil
  108. }
  109. func validateOptions(value reflect.Value, opt *fieldOptions) error {
  110. var found bool
  111. val := fmt.Sprint(value.Interface())
  112. for i := range opt.Options {
  113. if opt.Options[i] == val {
  114. found = true
  115. break
  116. }
  117. }
  118. if !found {
  119. return fmt.Errorf("field %q not in options", val)
  120. }
  121. return nil
  122. }
  123. func validateRange(value reflect.Value, opt *fieldOptions) error {
  124. var val float64
  125. switch v := value.Interface().(type) {
  126. case int:
  127. val = float64(v)
  128. case int8:
  129. val = float64(v)
  130. case int16:
  131. val = float64(v)
  132. case int32:
  133. val = float64(v)
  134. case int64:
  135. val = float64(v)
  136. case uint:
  137. val = float64(v)
  138. case uint8:
  139. val = float64(v)
  140. case uint16:
  141. val = float64(v)
  142. case uint32:
  143. val = float64(v)
  144. case uint64:
  145. val = float64(v)
  146. case float32:
  147. val = float64(v)
  148. case float64:
  149. val = v
  150. default:
  151. return fmt.Errorf("unknown support type for range %q", value.Type().String())
  152. }
  153. // validates [left, right], [left, right), (left, right], (left, right)
  154. if val < opt.Range.left ||
  155. (!opt.Range.leftInclude && val == opt.Range.left) ||
  156. val > opt.Range.right ||
  157. (!opt.Range.rightInclude && val == opt.Range.right) {
  158. return fmt.Errorf("%v out of range", value.Interface())
  159. }
  160. return nil
  161. }