decode_hooks.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package mapstructure
  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. // OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned.
  70. // If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages.
  71. func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc {
  72. return func(a, b reflect.Value) (interface{}, error) {
  73. var allErrs string
  74. var out interface{}
  75. var err error
  76. for _, f := range ff {
  77. out, err = DecodeHookExec(f, a, b)
  78. if err != nil {
  79. allErrs += err.Error() + "\n"
  80. continue
  81. }
  82. return out, nil
  83. }
  84. return nil, errors.New(allErrs)
  85. }
  86. }
  87. // StringToSliceHookFunc returns a DecodeHookFunc that converts
  88. // string to []string by splitting on the given sep.
  89. func StringToSliceHookFunc(sep string) DecodeHookFunc {
  90. return func(
  91. f reflect.Kind,
  92. t reflect.Kind,
  93. data interface{}) (interface{}, error) {
  94. if f != reflect.String || t != reflect.Slice {
  95. return data, nil
  96. }
  97. raw := data.(string)
  98. if raw == "" {
  99. return []string{}, nil
  100. }
  101. return strings.Split(raw, sep), nil
  102. }
  103. }
  104. // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
  105. // strings to time.Duration.
  106. func StringToTimeDurationHookFunc() DecodeHookFunc {
  107. return func(
  108. f reflect.Type,
  109. t reflect.Type,
  110. data interface{}) (interface{}, error) {
  111. if f.Kind() != reflect.String {
  112. return data, nil
  113. }
  114. if t != reflect.TypeOf(time.Duration(5)) {
  115. return data, nil
  116. }
  117. // Convert it by parsing
  118. return time.ParseDuration(data.(string))
  119. }
  120. }
  121. // StringToIPHookFunc returns a DecodeHookFunc that converts
  122. // strings to net.IP
  123. func StringToIPHookFunc() DecodeHookFunc {
  124. return func(
  125. f reflect.Type,
  126. t reflect.Type,
  127. data interface{}) (interface{}, error) {
  128. if f.Kind() != reflect.String {
  129. return data, nil
  130. }
  131. if t != reflect.TypeOf(net.IP{}) {
  132. return data, nil
  133. }
  134. // Convert it by parsing
  135. ip := net.ParseIP(data.(string))
  136. if ip == nil {
  137. return net.IP{}, fmt.Errorf("failed parsing ip %v", data)
  138. }
  139. return ip, nil
  140. }
  141. }
  142. // StringToIPNetHookFunc returns a DecodeHookFunc that converts
  143. // strings to net.IPNet
  144. func StringToIPNetHookFunc() 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(net.IPNet{}) {
  153. return data, nil
  154. }
  155. // Convert it by parsing
  156. _, net, err := net.ParseCIDR(data.(string))
  157. return net, err
  158. }
  159. }
  160. // StringToTimeHookFunc returns a DecodeHookFunc that converts
  161. // strings to time.Time.
  162. func StringToTimeHookFunc(layout string) DecodeHookFunc {
  163. return func(
  164. f reflect.Type,
  165. t reflect.Type,
  166. data interface{}) (interface{}, error) {
  167. if f.Kind() != reflect.String {
  168. return data, nil
  169. }
  170. if t != reflect.TypeOf(time.Time{}) {
  171. return data, nil
  172. }
  173. // Convert it by parsing
  174. return time.Parse(layout, data.(string))
  175. }
  176. }
  177. // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to
  178. // the decoder.
  179. //
  180. // Note that this is significantly different from the WeaklyTypedInput option
  181. // of the DecoderConfig.
  182. func WeaklyTypedHook(
  183. f reflect.Kind,
  184. t reflect.Kind,
  185. data interface{}) (interface{}, error) {
  186. dataVal := reflect.ValueOf(data)
  187. switch t {
  188. case reflect.String:
  189. switch f {
  190. case reflect.Bool:
  191. if dataVal.Bool() {
  192. return "1", nil
  193. }
  194. return "0", nil
  195. case reflect.Float32:
  196. return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
  197. case reflect.Int:
  198. return strconv.FormatInt(dataVal.Int(), 10), nil
  199. case reflect.Slice:
  200. dataType := dataVal.Type()
  201. elemKind := dataType.Elem().Kind()
  202. if elemKind == reflect.Uint8 {
  203. return string(dataVal.Interface().([]uint8)), nil
  204. }
  205. case reflect.Uint:
  206. return strconv.FormatUint(dataVal.Uint(), 10), nil
  207. }
  208. }
  209. return data, nil
  210. }
  211. func RecursiveStructToMapHookFunc() DecodeHookFunc {
  212. return func(f reflect.Value, t reflect.Value) (interface{}, error) {
  213. if f.Kind() != reflect.Struct {
  214. return f.Interface(), nil
  215. }
  216. var i interface{} = struct{}{}
  217. if t.Type() != reflect.TypeOf(&i).Elem() {
  218. return f.Interface(), nil
  219. }
  220. m := make(map[string]interface{})
  221. t.Set(reflect.ValueOf(m))
  222. return f.Interface(), nil
  223. }
  224. }
  225. // TextUnmarshallerHookFunc returns a DecodeHookFunc that applies
  226. // strings to the UnmarshalText function, when the target type
  227. // implements the encoding.TextUnmarshaler interface
  228. func TextUnmarshallerHookFunc() DecodeHookFuncType {
  229. return func(
  230. f reflect.Type,
  231. t reflect.Type,
  232. data interface{}) (interface{}, error) {
  233. if f.Kind() != reflect.String {
  234. return data, nil
  235. }
  236. result := reflect.New(t).Interface()
  237. unmarshaller, ok := result.(encoding.TextUnmarshaler)
  238. if !ok {
  239. return data, nil
  240. }
  241. if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil {
  242. return nil, err
  243. }
  244. return result, nil
  245. }
  246. }