decoder.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package schema
  5. import (
  6. "encoding"
  7. "errors"
  8. "fmt"
  9. "reflect"
  10. "strings"
  11. )
  12. // NewDecoder returns a new Decoder.
  13. func NewDecoder() *Decoder {
  14. return &Decoder{cache: newCache()}
  15. }
  16. // Decoder decodes values from a map[string][]string to a struct.
  17. type Decoder struct {
  18. cache *cache
  19. zeroEmpty bool
  20. ignoreUnknownKeys bool
  21. }
  22. // SetAliasTag changes the tag used to locate custom field aliases.
  23. // The default tag is "schema".
  24. func (d *Decoder) SetAliasTag(tag string) {
  25. d.cache.tag = tag
  26. }
  27. // ZeroEmpty controls the behaviour when the decoder encounters empty values
  28. // in a map.
  29. // If z is true and a key in the map has the empty string as a value
  30. // then the corresponding struct field is set to the zero value.
  31. // If z is false then empty strings are ignored.
  32. //
  33. // The default value is false, that is empty values do not change
  34. // the value of the struct field.
  35. func (d *Decoder) ZeroEmpty(z bool) {
  36. d.zeroEmpty = z
  37. }
  38. // IgnoreUnknownKeys controls the behaviour when the decoder encounters unknown
  39. // keys in the map.
  40. // If i is true and an unknown field is encountered, it is ignored. This is
  41. // similar to how unknown keys are handled by encoding/json.
  42. // If i is false then Decode will return an error. Note that any valid keys
  43. // will still be decoded in to the target struct.
  44. //
  45. // To preserve backwards compatibility, the default value is false.
  46. func (d *Decoder) IgnoreUnknownKeys(i bool) {
  47. d.ignoreUnknownKeys = i
  48. }
  49. // RegisterConverter registers a converter function for a custom type.
  50. func (d *Decoder) RegisterConverter(value interface{}, converterFunc Converter) {
  51. d.cache.regconv[reflect.TypeOf(value)] = converterFunc
  52. }
  53. // Decode decodes a map[string][]string to a struct.
  54. //
  55. // The first parameter must be a pointer to a struct.
  56. //
  57. // The second parameter is a map, typically url.Values from an HTTP request.
  58. // Keys are "paths" in dotted notation to the struct fields and nested structs.
  59. //
  60. // See the package documentation for a full explanation of the mechanics.
  61. func (d *Decoder) Decode(dst interface{}, src map[string][]string) error {
  62. v := reflect.ValueOf(dst)
  63. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
  64. return errors.New("schema: interface must be a pointer to struct")
  65. }
  66. v = v.Elem()
  67. t := v.Type()
  68. errors := MultiError{}
  69. for path, values := range src {
  70. if parts, err := d.cache.parsePath(path, t); err == nil {
  71. if err = d.decode(v, path, parts, values); err != nil {
  72. errors[path] = err
  73. }
  74. } else if !d.ignoreUnknownKeys {
  75. errors[path] = fmt.Errorf("schema: invalid path %q", path)
  76. }
  77. }
  78. if len(errors) > 0 {
  79. return errors
  80. }
  81. return d.checkRequired(t, src, "")
  82. }
  83. // checkRequired checks whether requred field empty
  84. //
  85. // check type t recursively if t has struct fields, and prefix is same as parsePath: in dotted notation
  86. //
  87. // src is the source map for decoding, we use it here to see if those required fields are included in src
  88. func (d *Decoder) checkRequired(t reflect.Type, src map[string][]string, prefix string) error {
  89. struc := d.cache.get(t)
  90. if struc == nil {
  91. // unexpect, cache.get never return nil
  92. return errors.New("cache fail")
  93. }
  94. for _, f := range struc.fields {
  95. if f.typ.Kind() == reflect.Struct {
  96. err := d.checkRequired(f.typ, src, prefix+f.alias+".")
  97. if err != nil {
  98. return err
  99. }
  100. }
  101. if f.required {
  102. key := f.alias
  103. if prefix != "" {
  104. key = prefix + key
  105. }
  106. if isEmpty(f.typ, src[key]) {
  107. return fmt.Errorf("%v is empty", key)
  108. }
  109. }
  110. }
  111. return nil
  112. }
  113. // isEmpty returns true if value is empty for specific type
  114. func isEmpty(t reflect.Type, value []string) bool {
  115. if len(value) == 0 {
  116. return true
  117. }
  118. switch t.Kind() {
  119. case boolType, float32Type, float64Type, intType, int8Type, int32Type, int64Type, stringType, uint8Type, uint16Type, uint32Type, uint64Type:
  120. return len(value[0]) == 0
  121. }
  122. return false
  123. }
  124. // decode fills a struct field using a parsed path.
  125. func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values []string) error {
  126. // Get the field walking the struct fields by index.
  127. for _, name := range parts[0].path {
  128. if v.Type().Kind() == reflect.Ptr {
  129. if v.IsNil() {
  130. v.Set(reflect.New(v.Type().Elem()))
  131. }
  132. v = v.Elem()
  133. }
  134. v = v.FieldByName(name)
  135. }
  136. // Don't even bother for unexported fields.
  137. if !v.CanSet() {
  138. return nil
  139. }
  140. // Dereference if needed.
  141. t := v.Type()
  142. if t.Kind() == reflect.Ptr {
  143. t = t.Elem()
  144. if v.IsNil() {
  145. v.Set(reflect.New(t))
  146. }
  147. v = v.Elem()
  148. }
  149. // Slice of structs. Let's go recursive.
  150. if len(parts) > 1 {
  151. idx := parts[0].index
  152. if v.IsNil() || v.Len() < idx+1 {
  153. value := reflect.MakeSlice(t, idx+1, idx+1)
  154. if v.Len() < idx+1 {
  155. // Resize it.
  156. reflect.Copy(value, v)
  157. }
  158. v.Set(value)
  159. }
  160. return d.decode(v.Index(idx), path, parts[1:], values)
  161. }
  162. // Get the converter early in case there is one for a slice type.
  163. conv := d.cache.converter(t)
  164. if conv == nil && t.Kind() == reflect.Slice {
  165. var items []reflect.Value
  166. elemT := t.Elem()
  167. isPtrElem := elemT.Kind() == reflect.Ptr
  168. if isPtrElem {
  169. elemT = elemT.Elem()
  170. }
  171. // Try to get a converter for the element type.
  172. conv := d.cache.converter(elemT)
  173. if conv == nil {
  174. // As we are not dealing with slice of structs here, we don't need to check if the type
  175. // implements TextUnmarshaler interface
  176. return fmt.Errorf("schema: converter not found for %v", elemT)
  177. }
  178. for key, value := range values {
  179. if value == "" {
  180. if d.zeroEmpty {
  181. items = append(items, reflect.Zero(elemT))
  182. }
  183. } else if item := conv(value); item.IsValid() {
  184. if isPtrElem {
  185. ptr := reflect.New(elemT)
  186. ptr.Elem().Set(item)
  187. item = ptr
  188. }
  189. if item.Type() != elemT && !isPtrElem {
  190. item = item.Convert(elemT)
  191. }
  192. items = append(items, item)
  193. } else {
  194. if strings.Contains(value, ",") {
  195. values := strings.Split(value, ",")
  196. for _, value := range values {
  197. if value == "" {
  198. if d.zeroEmpty {
  199. items = append(items, reflect.Zero(elemT))
  200. }
  201. } else if item := conv(value); item.IsValid() {
  202. if isPtrElem {
  203. ptr := reflect.New(elemT)
  204. ptr.Elem().Set(item)
  205. item = ptr
  206. }
  207. if item.Type() != elemT && !isPtrElem {
  208. item = item.Convert(elemT)
  209. }
  210. items = append(items, item)
  211. } else {
  212. return ConversionError{
  213. Key: path,
  214. Type: elemT,
  215. Index: key,
  216. }
  217. }
  218. }
  219. } else {
  220. return ConversionError{
  221. Key: path,
  222. Type: elemT,
  223. Index: key,
  224. }
  225. }
  226. }
  227. }
  228. value := reflect.Append(reflect.MakeSlice(t, 0, 0), items...)
  229. v.Set(value)
  230. } else {
  231. val := ""
  232. // Use the last value provided if any values were provided
  233. if len(values) > 0 {
  234. val = values[len(values)-1]
  235. }
  236. if val == "" {
  237. if d.zeroEmpty {
  238. v.Set(reflect.Zero(t))
  239. }
  240. } else if conv != nil {
  241. if value := conv(val); value.IsValid() {
  242. v.Set(value.Convert(t))
  243. } else {
  244. return ConversionError{
  245. Key: path,
  246. Type: t,
  247. Index: -1,
  248. }
  249. }
  250. } else {
  251. // When there's no registered conversion for the custom type, we will check if the type
  252. // implements the TextUnmarshaler interface. As the UnmarshalText function should be applied
  253. // to the pointer of the type, we convert the value to pointer.
  254. if v.CanAddr() {
  255. v = v.Addr()
  256. }
  257. if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
  258. if err := u.UnmarshalText([]byte(val)); err != nil {
  259. return ConversionError{
  260. Key: path,
  261. Type: t,
  262. Index: -1,
  263. Err: err,
  264. }
  265. }
  266. } else {
  267. return fmt.Errorf("schema: converter not found for %v", t)
  268. }
  269. }
  270. }
  271. return nil
  272. }
  273. // Errors ---------------------------------------------------------------------
  274. // ConversionError stores information about a failed conversion.
  275. type ConversionError struct {
  276. Key string // key from the source map.
  277. Type reflect.Type // expected type of elem
  278. Index int // index for multi-value fields; -1 for single-value fields.
  279. Err error // low-level error (when it exists)
  280. }
  281. func (e ConversionError) Error() string {
  282. var output string
  283. if e.Index < 0 {
  284. output = fmt.Sprintf("schema: error converting value for %q", e.Key)
  285. } else {
  286. output = fmt.Sprintf("schema: error converting value for index %d of %q",
  287. e.Index, e.Key)
  288. }
  289. if e.Err != nil {
  290. output = fmt.Sprintf("%s. Details: %s", output, e.Err)
  291. }
  292. return output
  293. }
  294. // MultiError stores multiple decoding errors.
  295. //
  296. // Borrowed from the App Engine SDK.
  297. type MultiError map[string]error
  298. func (e MultiError) Error() string {
  299. s := ""
  300. for _, err := range e {
  301. s = err.Error()
  302. break
  303. }
  304. switch len(e) {
  305. case 0:
  306. return "(0 errors)"
  307. case 1:
  308. return s
  309. case 2:
  310. return s + " (and 1 other error)"
  311. }
  312. return fmt.Sprintf("%s (and %d other errors)", s, len(e)-1)
  313. }