decode_hooks.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package mhayaMapStructure
  2. import (
  3. "encoding"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns
  13. // it into the proper DecodeHookFunc type, such as DecodeHookFuncType.
  14. func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc {
  15. // Create variables here so we can reference them with the reflect pkg
  16. var f1 DecodeHookFuncType
  17. var f2 DecodeHookFuncKind
  18. var f3 DecodeHookFuncValue
  19. // Fill in the variables into this interface and the rest is done
  20. // automatically using the reflect package.
  21. potential := []interface{}{f1, f2, f3}
  22. v := reflect.ValueOf(h)
  23. vt := v.Type()
  24. for _, raw := range potential {
  25. pt := reflect.ValueOf(raw).Type()
  26. if vt.ConvertibleTo(pt) {
  27. return v.Convert(pt).Interface()
  28. }
  29. }
  30. return nil
  31. }
  32. // DecodeHookExec executes the given decode hook. This should be used
  33. // since it'll naturally degrade to the older backwards compatible DecodeHookFunc
  34. // that took reflect.Kind instead of reflect.Type.
  35. func DecodeHookExec(
  36. raw DecodeHookFunc,
  37. from reflect.Value, to reflect.Value) (interface{}, error) {
  38. switch f := typedDecodeHook(raw).(type) {
  39. case DecodeHookFuncType:
  40. return f(from.Type(), to.Type(), from.Interface())
  41. case DecodeHookFuncKind:
  42. return f(from.Kind(), to.Kind(), from.Interface())
  43. case DecodeHookFuncValue:
  44. return f(from, to)
  45. default:
  46. return nil, errors.New("invalid decode hook signature")
  47. }
  48. }
  49. // ComposeDecodeHookFunc creates a single DecodeHookFunc that
  50. // automatically composes multiple DecodeHookFuncs.
  51. //
  52. // The composed funcs are called in order, with the result of the
  53. // previous transformation.
  54. func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
  55. return func(f reflect.Value, t reflect.Value) (interface{}, error) {
  56. var err error
  57. data := f.Interface()
  58. newFrom := f
  59. for _, f1 := range fs {
  60. data, err = DecodeHookExec(f1, newFrom, t)
  61. if err != nil {
  62. return nil, err
  63. }
  64. newFrom = reflect.ValueOf(data)
  65. }
  66. return data, nil
  67. }
  68. }
  69. // StringToSliceHookFunc returns a DecodeHookFunc that converts
  70. // string to []string by splitting on the given sep.
  71. func StringToSliceHookFunc(sep string) DecodeHookFunc {
  72. return func(
  73. f reflect.Kind,
  74. t reflect.Kind,
  75. data interface{}) (interface{}, error) {
  76. if f != reflect.String || t != reflect.Slice {
  77. return data, nil
  78. }
  79. raw := data.(string)
  80. if raw == "" {
  81. return []string{}, nil
  82. }
  83. return strings.Split(raw, sep), nil
  84. }
  85. }
  86. // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
  87. // strings to time.Duration.
  88. func StringToTimeDurationHookFunc() DecodeHookFunc {
  89. return func(
  90. f reflect.Type,
  91. t reflect.Type,
  92. data interface{}) (interface{}, error) {
  93. if f.Kind() != reflect.String {
  94. return data, nil
  95. }
  96. if t != reflect.TypeOf(time.Duration(5)) {
  97. return data, nil
  98. }
  99. // Convert it by parsing
  100. return time.ParseDuration(data.(string))
  101. }
  102. }
  103. // StringToIPHookFunc returns a DecodeHookFunc that converts
  104. // strings to net.IP
  105. func StringToIPHookFunc() DecodeHookFunc {
  106. return func(
  107. f reflect.Type,
  108. t reflect.Type,
  109. data interface{}) (interface{}, error) {
  110. if f.Kind() != reflect.String {
  111. return data, nil
  112. }
  113. if t != reflect.TypeOf(net.IP{}) {
  114. return data, nil
  115. }
  116. // Convert it by parsing
  117. ip := net.ParseIP(data.(string))
  118. if ip == nil {
  119. return net.IP{}, fmt.Errorf("failed parsing ip %v", data)
  120. }
  121. return ip, nil
  122. }
  123. }
  124. // StringToIPNetHookFunc returns a DecodeHookFunc that converts
  125. // strings to net.IPNet
  126. func StringToIPNetHookFunc() DecodeHookFunc {
  127. return func(
  128. f reflect.Type,
  129. t reflect.Type,
  130. data interface{}) (interface{}, error) {
  131. if f.Kind() != reflect.String {
  132. return data, nil
  133. }
  134. if t != reflect.TypeOf(net.IPNet{}) {
  135. return data, nil
  136. }
  137. // Convert it by parsing
  138. _, net, err := net.ParseCIDR(data.(string))
  139. return net, err
  140. }
  141. }
  142. // StringToTimeHookFunc returns a DecodeHookFunc that converts
  143. // strings to time.Time.
  144. func StringToTimeHookFunc(layout string) DecodeHookFunc {
  145. return func(
  146. f reflect.Type,
  147. t reflect.Type,
  148. data interface{}) (interface{}, error) {
  149. if f.Kind() != reflect.String {
  150. return data, nil
  151. }
  152. if t != reflect.TypeOf(time.Time{}) {
  153. return data, nil
  154. }
  155. // Convert it by parsing
  156. return time.Parse(layout, data.(string))
  157. }
  158. }
  159. // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to
  160. // the decoder.
  161. //
  162. // Note that this is significantly different from the WeaklyTypedInput option
  163. // of the DecoderConfig.
  164. func WeaklyTypedHook(
  165. f reflect.Kind,
  166. t reflect.Kind,
  167. data interface{}) (interface{}, error) {
  168. dataVal := reflect.ValueOf(data)
  169. switch t {
  170. case reflect.String:
  171. switch f {
  172. case reflect.Bool:
  173. if dataVal.Bool() {
  174. return "1", nil
  175. }
  176. return "0", nil
  177. case reflect.Float32:
  178. return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
  179. case reflect.Int:
  180. return strconv.FormatInt(dataVal.Int(), 10), nil
  181. case reflect.Slice:
  182. dataType := dataVal.Type()
  183. elemKind := dataType.Elem().Kind()
  184. if elemKind == reflect.Uint8 {
  185. return string(dataVal.Interface().([]uint8)), nil
  186. }
  187. case reflect.Uint:
  188. return strconv.FormatUint(dataVal.Uint(), 10), nil
  189. }
  190. }
  191. return data, nil
  192. }
  193. func RecursiveStructToMapHookFunc() DecodeHookFunc {
  194. return func(f reflect.Value, t reflect.Value) (interface{}, error) {
  195. if f.Kind() != reflect.Struct {
  196. return f.Interface(), nil
  197. }
  198. var i interface{} = struct{}{}
  199. if t.Type() != reflect.TypeOf(&i).Elem() {
  200. return f.Interface(), nil
  201. }
  202. m := make(map[string]interface{})
  203. t.Set(reflect.ValueOf(m))
  204. return f.Interface(), nil
  205. }
  206. }
  207. // TextUnmarshallerHookFunc returns a DecodeHookFunc that applies
  208. // strings to the UnmarshalText function, when the target type
  209. // implements the encoding.TextUnmarshaler interface
  210. func TextUnmarshallerHookFunc() DecodeHookFuncType {
  211. return func(
  212. f reflect.Type,
  213. t reflect.Type,
  214. data interface{}) (interface{}, error) {
  215. if f.Kind() != reflect.String {
  216. return data, nil
  217. }
  218. result := reflect.New(t).Interface()
  219. unmarshaller, ok := result.(encoding.TextUnmarshaler)
  220. if !ok {
  221. return data, nil
  222. }
  223. if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil {
  224. return nil, err
  225. }
  226. return result, nil
  227. }
  228. }