decoder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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.registerConverter(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 required fields are 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. if !f.anon {
  99. return err
  100. }
  101. // check embedded parent field.
  102. err2 := d.checkRequired(f.typ, src, prefix)
  103. if err2 != nil {
  104. return err
  105. }
  106. }
  107. }
  108. if f.required {
  109. key := f.alias
  110. if prefix != "" {
  111. key = prefix + key
  112. }
  113. if isEmpty(f.typ, src[key]) {
  114. return fmt.Errorf("%v is empty", key)
  115. }
  116. }
  117. }
  118. return nil
  119. }
  120. // isEmpty returns true if value is empty for specific type
  121. func isEmpty(t reflect.Type, value []string) bool {
  122. if len(value) == 0 {
  123. return true
  124. }
  125. switch t.Kind() {
  126. case boolType, float32Type, float64Type, intType, int8Type, int32Type, int64Type, stringType, uint8Type, uint16Type, uint32Type, uint64Type:
  127. return len(value[0]) == 0
  128. }
  129. return false
  130. }
  131. // decode fills a struct field using a parsed path.
  132. func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values []string) error {
  133. // Get the field walking the struct fields by index.
  134. for _, name := range parts[0].path {
  135. if v.Type().Kind() == reflect.Ptr {
  136. if v.IsNil() {
  137. v.Set(reflect.New(v.Type().Elem()))
  138. }
  139. v = v.Elem()
  140. }
  141. v = v.FieldByName(name)
  142. }
  143. // Don't even bother for unexported fields.
  144. if !v.CanSet() {
  145. return nil
  146. }
  147. // Dereference if needed.
  148. t := v.Type()
  149. if t.Kind() == reflect.Ptr {
  150. t = t.Elem()
  151. if v.IsNil() {
  152. v.Set(reflect.New(t))
  153. }
  154. v = v.Elem()
  155. }
  156. // Slice of structs. Let's go recursive.
  157. if len(parts) > 1 {
  158. idx := parts[0].index
  159. if v.IsNil() || v.Len() < idx+1 {
  160. value := reflect.MakeSlice(t, idx+1, idx+1)
  161. if v.Len() < idx+1 {
  162. // Resize it.
  163. reflect.Copy(value, v)
  164. }
  165. v.Set(value)
  166. }
  167. return d.decode(v.Index(idx), path, parts[1:], values)
  168. }
  169. // Get the converter early in case there is one for a slice type.
  170. conv := d.cache.converter(t)
  171. if conv == nil && t.Kind() == reflect.Slice {
  172. var items []reflect.Value
  173. elemT := t.Elem()
  174. isPtrElem := elemT.Kind() == reflect.Ptr
  175. if isPtrElem {
  176. elemT = elemT.Elem()
  177. }
  178. // Try to get a converter for the element type.
  179. conv := d.cache.converter(elemT)
  180. if conv == nil {
  181. conv = builtinConverters[elemT.Kind()]
  182. if conv == nil {
  183. // As we are not dealing with slice of structs here, we don't need to check if the type
  184. // implements TextUnmarshaler interface
  185. return fmt.Errorf("schema: converter not found for %v", elemT)
  186. }
  187. }
  188. for key, value := range values {
  189. if value == "" {
  190. if d.zeroEmpty {
  191. items = append(items, reflect.Zero(elemT))
  192. }
  193. } else if m := isTextUnmarshaler(v); m.IsValid {
  194. u := reflect.New(elemT)
  195. if m.IsPtr {
  196. u = reflect.New(reflect.PtrTo(elemT).Elem())
  197. }
  198. if err := u.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)); err != nil {
  199. return ConversionError{
  200. Key: path,
  201. Type: t,
  202. Index: key,
  203. Err: err,
  204. }
  205. }
  206. if m.IsPtr {
  207. items = append(items, u.Elem().Addr())
  208. } else if u.Kind() == reflect.Ptr {
  209. items = append(items, u.Elem())
  210. } else {
  211. items = append(items, u)
  212. }
  213. } else if item := conv(value); item.IsValid() {
  214. if isPtrElem {
  215. ptr := reflect.New(elemT)
  216. ptr.Elem().Set(item)
  217. item = ptr
  218. }
  219. if item.Type() != elemT && !isPtrElem {
  220. item = item.Convert(elemT)
  221. }
  222. items = append(items, item)
  223. } else {
  224. if strings.Contains(value, ",") {
  225. values := strings.Split(value, ",")
  226. for _, value := range values {
  227. if value == "" {
  228. if d.zeroEmpty {
  229. items = append(items, reflect.Zero(elemT))
  230. }
  231. } else if item := conv(value); item.IsValid() {
  232. if isPtrElem {
  233. ptr := reflect.New(elemT)
  234. ptr.Elem().Set(item)
  235. item = ptr
  236. }
  237. if item.Type() != elemT && !isPtrElem {
  238. item = item.Convert(elemT)
  239. }
  240. items = append(items, item)
  241. } else {
  242. return ConversionError{
  243. Key: path,
  244. Type: elemT,
  245. Index: key,
  246. }
  247. }
  248. }
  249. } else {
  250. return ConversionError{
  251. Key: path,
  252. Type: elemT,
  253. Index: key,
  254. }
  255. }
  256. }
  257. }
  258. value := reflect.Append(reflect.MakeSlice(t, 0, 0), items...)
  259. v.Set(value)
  260. } else {
  261. val := ""
  262. // Use the last value provided if any values were provided
  263. if len(values) > 0 {
  264. val = values[len(values)-1]
  265. }
  266. if val == "" {
  267. if d.zeroEmpty {
  268. v.Set(reflect.Zero(t))
  269. }
  270. } else if conv != nil {
  271. if value := conv(val); value.IsValid() {
  272. v.Set(value.Convert(t))
  273. } else {
  274. return ConversionError{
  275. Key: path,
  276. Type: t,
  277. Index: -1,
  278. }
  279. }
  280. } else if m := isTextUnmarshaler(v); m.IsValid {
  281. // If the value implements the encoding.TextUnmarshaler interface
  282. // apply UnmarshalText as the converter
  283. if err := m.Unmarshaler.UnmarshalText([]byte(val)); err != nil {
  284. return ConversionError{
  285. Key: path,
  286. Type: t,
  287. Index: -1,
  288. Err: err,
  289. }
  290. }
  291. } else if conv := builtinConverters[t.Kind()]; conv != nil {
  292. if value := conv(val); value.IsValid() {
  293. v.Set(value.Convert(t))
  294. } else {
  295. return ConversionError{
  296. Key: path,
  297. Type: t,
  298. Index: -1,
  299. }
  300. }
  301. } else {
  302. return fmt.Errorf("schema: converter not found for %v", t)
  303. }
  304. }
  305. return nil
  306. }
  307. func isTextUnmarshaler(v reflect.Value) unmarshaler {
  308. // Create a new unmarshaller instance
  309. m := unmarshaler{}
  310. // As the UnmarshalText function should be applied
  311. // to the pointer of the type, we convert the value to pointer.
  312. if v.CanAddr() {
  313. v = v.Addr()
  314. }
  315. if m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler); m.IsValid {
  316. return m
  317. }
  318. // if v is []T or *[]T create new T
  319. t := v.Type()
  320. if t.Kind() == reflect.Ptr {
  321. t = t.Elem()
  322. }
  323. if t.Kind() == reflect.Slice {
  324. // if t is a pointer slice, check if it implements encoding.TextUnmarshaler
  325. if t = t.Elem(); t.Kind() == reflect.Ptr {
  326. t = reflect.PtrTo(t.Elem())
  327. v = reflect.Zero(t)
  328. m.IsPtr = true
  329. m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler)
  330. return m
  331. }
  332. }
  333. v = reflect.New(t)
  334. m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler)
  335. return m
  336. }
  337. // TextUnmarshaler helpers ----------------------------------------------------
  338. // unmarshaller contains information about a TextUnmarshaler type
  339. type unmarshaler struct {
  340. Unmarshaler encoding.TextUnmarshaler
  341. IsPtr bool
  342. IsValid bool
  343. }
  344. // Errors ---------------------------------------------------------------------
  345. // ConversionError stores information about a failed conversion.
  346. type ConversionError struct {
  347. Key string // key from the source map.
  348. Type reflect.Type // expected type of elem
  349. Index int // index for multi-value fields; -1 for single-value fields.
  350. Err error // low-level error (when it exists)
  351. }
  352. func (e ConversionError) Error() string {
  353. var output string
  354. if e.Index < 0 {
  355. output = fmt.Sprintf("schema: error converting value for %q", e.Key)
  356. } else {
  357. output = fmt.Sprintf("schema: error converting value for index %d of %q",
  358. e.Index, e.Key)
  359. }
  360. if e.Err != nil {
  361. output = fmt.Sprintf("%s. Details: %s", output, e.Err)
  362. }
  363. return output
  364. }
  365. // MultiError stores multiple decoding errors.
  366. //
  367. // Borrowed from the App Engine SDK.
  368. type MultiError map[string]error
  369. func (e MultiError) Error() string {
  370. s := ""
  371. for _, err := range e {
  372. s = err.Error()
  373. break
  374. }
  375. switch len(e) {
  376. case 0:
  377. return "(0 errors)"
  378. case 1:
  379. return s
  380. case 2:
  381. return s + " (and 1 other error)"
  382. }
  383. return fmt.Sprintf("%s (and %d other errors)", s, len(e)-1)
  384. }