decoder.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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] = UnknownKeyError{Key: path}
  76. }
  77. }
  78. errors.merge(d.checkRequired(t, src))
  79. if len(errors) > 0 {
  80. return errors
  81. }
  82. return nil
  83. }
  84. // checkRequired checks whether required fields are empty
  85. //
  86. // check type t recursively if t has struct fields.
  87. //
  88. // src is the source map for decoding, we use it here to see if those required fields are included in src
  89. func (d *Decoder) checkRequired(t reflect.Type, src map[string][]string) MultiError {
  90. m, errs := d.findRequiredFields(t, "", "")
  91. for key, fields := range m {
  92. if isEmptyFields(fields, src) {
  93. errs[key] = EmptyFieldError{Key: key}
  94. }
  95. }
  96. return errs
  97. }
  98. // findRequiredFields recursively searches the struct type t for required fields.
  99. //
  100. // canonicalPrefix and searchPrefix are used to resolve full paths in dotted notation
  101. // for nested struct fields. canonicalPrefix is a complete path which never omits
  102. // any embedded struct fields. searchPrefix is a user-friendly path which may omit
  103. // some embedded struct fields to point promoted fields.
  104. func (d *Decoder) findRequiredFields(t reflect.Type, canonicalPrefix, searchPrefix string) (map[string][]fieldWithPrefix, MultiError) {
  105. struc := d.cache.get(t)
  106. if struc == nil {
  107. // unexpect, cache.get never return nil
  108. return nil, MultiError{canonicalPrefix + "*": errors.New("cache fail")}
  109. }
  110. m := map[string][]fieldWithPrefix{}
  111. errs := MultiError{}
  112. for _, f := range struc.fields {
  113. if f.typ.Kind() == reflect.Struct {
  114. fcprefix := canonicalPrefix + f.canonicalAlias + "."
  115. for _, fspath := range f.paths(searchPrefix) {
  116. fm, ferrs := d.findRequiredFields(f.typ, fcprefix, fspath+".")
  117. for key, fields := range fm {
  118. m[key] = append(m[key], fields...)
  119. }
  120. errs.merge(ferrs)
  121. }
  122. }
  123. if f.isRequired {
  124. key := canonicalPrefix + f.canonicalAlias
  125. m[key] = append(m[key], fieldWithPrefix{
  126. fieldInfo: f,
  127. prefix: searchPrefix,
  128. })
  129. }
  130. }
  131. return m, errs
  132. }
  133. type fieldWithPrefix struct {
  134. *fieldInfo
  135. prefix string
  136. }
  137. // isEmptyFields returns true if all of specified fields are empty.
  138. func isEmptyFields(fields []fieldWithPrefix, src map[string][]string) bool {
  139. for _, f := range fields {
  140. for _, path := range f.paths(f.prefix) {
  141. v, ok := src[path]
  142. if ok && !isEmpty(f.typ, v) {
  143. return false
  144. }
  145. for key := range src {
  146. if !isEmpty(f.typ, src[key]) && strings.HasPrefix(key, path) {
  147. return false
  148. }
  149. }
  150. }
  151. }
  152. return true
  153. }
  154. // isEmpty returns true if value is empty for specific type
  155. func isEmpty(t reflect.Type, value []string) bool {
  156. if len(value) == 0 {
  157. return true
  158. }
  159. switch t.Kind() {
  160. case boolType, float32Type, float64Type, intType, int8Type, int32Type, int64Type, stringType, uint8Type, uint16Type, uint32Type, uint64Type:
  161. return len(value[0]) == 0
  162. }
  163. return false
  164. }
  165. // decode fills a struct field using a parsed path.
  166. func (d *Decoder) decode(v reflect.Value, path string, parts []pathPart, values []string) error {
  167. // Get the field walking the struct fields by index.
  168. for _, name := range parts[0].path {
  169. if v.Type().Kind() == reflect.Ptr {
  170. if v.IsNil() {
  171. v.Set(reflect.New(v.Type().Elem()))
  172. }
  173. v = v.Elem()
  174. }
  175. // alloc embedded structs
  176. if v.Type().Kind() == reflect.Struct {
  177. for i := 0; i < v.NumField(); i++ {
  178. field := v.Field(i)
  179. if field.Type().Kind() == reflect.Ptr && field.IsNil() && v.Type().Field(i).Anonymous == true {
  180. field.Set(reflect.New(field.Type().Elem()))
  181. }
  182. }
  183. }
  184. v = v.FieldByName(name)
  185. }
  186. // Don't even bother for unexported fields.
  187. if !v.CanSet() {
  188. return nil
  189. }
  190. // Dereference if needed.
  191. t := v.Type()
  192. if t.Kind() == reflect.Ptr {
  193. t = t.Elem()
  194. if v.IsNil() {
  195. v.Set(reflect.New(t))
  196. }
  197. v = v.Elem()
  198. }
  199. // Slice of structs. Let's go recursive.
  200. if len(parts) > 1 {
  201. idx := parts[0].index
  202. if v.IsNil() || v.Len() < idx+1 {
  203. value := reflect.MakeSlice(t, idx+1, idx+1)
  204. if v.Len() < idx+1 {
  205. // Resize it.
  206. reflect.Copy(value, v)
  207. }
  208. v.Set(value)
  209. }
  210. return d.decode(v.Index(idx), path, parts[1:], values)
  211. }
  212. // Get the converter early in case there is one for a slice type.
  213. conv := d.cache.converter(t)
  214. m := isTextUnmarshaler(v)
  215. if conv == nil && t.Kind() == reflect.Slice && m.IsSliceElement {
  216. var items []reflect.Value
  217. elemT := t.Elem()
  218. isPtrElem := elemT.Kind() == reflect.Ptr
  219. if isPtrElem {
  220. elemT = elemT.Elem()
  221. }
  222. // Try to get a converter for the element type.
  223. conv := d.cache.converter(elemT)
  224. if conv == nil {
  225. conv = builtinConverters[elemT.Kind()]
  226. if conv == nil {
  227. // As we are not dealing with slice of structs here, we don't need to check if the type
  228. // implements TextUnmarshaler interface
  229. return fmt.Errorf("schema: converter not found for %v", elemT)
  230. }
  231. }
  232. for key, value := range values {
  233. if value == "" {
  234. if d.zeroEmpty {
  235. items = append(items, reflect.Zero(elemT))
  236. }
  237. } else if m.IsValid {
  238. u := reflect.New(elemT)
  239. if m.IsSliceElementPtr {
  240. u = reflect.New(reflect.PtrTo(elemT).Elem())
  241. }
  242. if err := u.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)); err != nil {
  243. return ConversionError{
  244. Key: path,
  245. Type: t,
  246. Index: key,
  247. Err: err,
  248. }
  249. }
  250. if m.IsSliceElementPtr {
  251. items = append(items, u.Elem().Addr())
  252. } else if u.Kind() == reflect.Ptr {
  253. items = append(items, u.Elem())
  254. } else {
  255. items = append(items, u)
  256. }
  257. } else if item := conv(value); item.IsValid() {
  258. if isPtrElem {
  259. ptr := reflect.New(elemT)
  260. ptr.Elem().Set(item)
  261. item = ptr
  262. }
  263. if item.Type() != elemT && !isPtrElem {
  264. item = item.Convert(elemT)
  265. }
  266. items = append(items, item)
  267. } else {
  268. if strings.Contains(value, ",") {
  269. values := strings.Split(value, ",")
  270. for _, value := range values {
  271. if value == "" {
  272. if d.zeroEmpty {
  273. items = append(items, reflect.Zero(elemT))
  274. }
  275. } else if item := conv(value); item.IsValid() {
  276. if isPtrElem {
  277. ptr := reflect.New(elemT)
  278. ptr.Elem().Set(item)
  279. item = ptr
  280. }
  281. if item.Type() != elemT && !isPtrElem {
  282. item = item.Convert(elemT)
  283. }
  284. items = append(items, item)
  285. } else {
  286. return ConversionError{
  287. Key: path,
  288. Type: elemT,
  289. Index: key,
  290. }
  291. }
  292. }
  293. } else {
  294. return ConversionError{
  295. Key: path,
  296. Type: elemT,
  297. Index: key,
  298. }
  299. }
  300. }
  301. }
  302. value := reflect.Append(reflect.MakeSlice(t, 0, 0), items...)
  303. v.Set(value)
  304. } else {
  305. val := ""
  306. // Use the last value provided if any values were provided
  307. if len(values) > 0 {
  308. val = values[len(values)-1]
  309. }
  310. if conv != nil {
  311. if value := conv(val); value.IsValid() {
  312. v.Set(value.Convert(t))
  313. } else {
  314. return ConversionError{
  315. Key: path,
  316. Type: t,
  317. Index: -1,
  318. }
  319. }
  320. } else if m.IsValid {
  321. if m.IsPtr {
  322. u := reflect.New(v.Type())
  323. if err := u.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(val)); err != nil {
  324. return ConversionError{
  325. Key: path,
  326. Type: t,
  327. Index: -1,
  328. Err: err,
  329. }
  330. }
  331. v.Set(reflect.Indirect(u))
  332. } else {
  333. // If the value implements the encoding.TextUnmarshaler interface
  334. // apply UnmarshalText as the converter
  335. if err := m.Unmarshaler.UnmarshalText([]byte(val)); err != nil {
  336. return ConversionError{
  337. Key: path,
  338. Type: t,
  339. Index: -1,
  340. Err: err,
  341. }
  342. }
  343. }
  344. } else if val == "" {
  345. if d.zeroEmpty {
  346. v.Set(reflect.Zero(t))
  347. }
  348. } else if conv := builtinConverters[t.Kind()]; conv != nil {
  349. if value := conv(val); value.IsValid() {
  350. v.Set(value.Convert(t))
  351. } else {
  352. return ConversionError{
  353. Key: path,
  354. Type: t,
  355. Index: -1,
  356. }
  357. }
  358. } else {
  359. return fmt.Errorf("schema: converter not found for %v", t)
  360. }
  361. }
  362. return nil
  363. }
  364. func isTextUnmarshaler(v reflect.Value) unmarshaler {
  365. // Create a new unmarshaller instance
  366. m := unmarshaler{}
  367. if m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler); m.IsValid {
  368. return m
  369. }
  370. // As the UnmarshalText function should be applied to the pointer of the
  371. // type, we check that type to see if it implements the necessary
  372. // method.
  373. if m.Unmarshaler, m.IsValid = reflect.New(v.Type()).Interface().(encoding.TextUnmarshaler); m.IsValid {
  374. m.IsPtr = true
  375. return m
  376. }
  377. // if v is []T or *[]T create new T
  378. t := v.Type()
  379. if t.Kind() == reflect.Ptr {
  380. t = t.Elem()
  381. }
  382. if t.Kind() == reflect.Slice {
  383. // Check if the slice implements encoding.TextUnmarshaller
  384. if m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler); m.IsValid {
  385. return m
  386. }
  387. // If t is a pointer slice, check if its elements implement
  388. // encoding.TextUnmarshaler
  389. m.IsSliceElement = true
  390. if t = t.Elem(); t.Kind() == reflect.Ptr {
  391. t = reflect.PtrTo(t.Elem())
  392. v = reflect.Zero(t)
  393. m.IsSliceElementPtr = true
  394. m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler)
  395. return m
  396. }
  397. }
  398. v = reflect.New(t)
  399. m.Unmarshaler, m.IsValid = v.Interface().(encoding.TextUnmarshaler)
  400. return m
  401. }
  402. // TextUnmarshaler helpers ----------------------------------------------------
  403. // unmarshaller contains information about a TextUnmarshaler type
  404. type unmarshaler struct {
  405. Unmarshaler encoding.TextUnmarshaler
  406. // IsValid indicates whether the resolved type indicated by the other
  407. // flags implements the encoding.TextUnmarshaler interface.
  408. IsValid bool
  409. // IsPtr indicates that the resolved type is the pointer of the original
  410. // type.
  411. IsPtr bool
  412. // IsSliceElement indicates that the resolved type is a slice element of
  413. // the original type.
  414. IsSliceElement bool
  415. // IsSliceElementPtr indicates that the resolved type is a pointer to a
  416. // slice element of the original type.
  417. IsSliceElementPtr bool
  418. }
  419. // Errors ---------------------------------------------------------------------
  420. // ConversionError stores information about a failed conversion.
  421. type ConversionError struct {
  422. Key string // key from the source map.
  423. Type reflect.Type // expected type of elem
  424. Index int // index for multi-value fields; -1 for single-value fields.
  425. Err error // low-level error (when it exists)
  426. }
  427. func (e ConversionError) Error() string {
  428. var output string
  429. if e.Index < 0 {
  430. output = fmt.Sprintf("schema: error converting value for %q", e.Key)
  431. } else {
  432. output = fmt.Sprintf("schema: error converting value for index %d of %q",
  433. e.Index, e.Key)
  434. }
  435. if e.Err != nil {
  436. output = fmt.Sprintf("%s. Details: %s", output, e.Err)
  437. }
  438. return output
  439. }
  440. // UnknownKeyError stores information about an unknown key in the source map.
  441. type UnknownKeyError struct {
  442. Key string // key from the source map.
  443. }
  444. func (e UnknownKeyError) Error() string {
  445. return fmt.Sprintf("schema: invalid path %q", e.Key)
  446. }
  447. // EmptyFieldError stores information about an empty required field.
  448. type EmptyFieldError struct {
  449. Key string // required key in the source map.
  450. }
  451. func (e EmptyFieldError) Error() string {
  452. return fmt.Sprintf("%v is empty", e.Key)
  453. }
  454. // MultiError stores multiple decoding errors.
  455. //
  456. // Borrowed from the App Engine SDK.
  457. type MultiError map[string]error
  458. func (e MultiError) Error() string {
  459. s := ""
  460. for _, err := range e {
  461. s = err.Error()
  462. break
  463. }
  464. switch len(e) {
  465. case 0:
  466. return "(0 errors)"
  467. case 1:
  468. return s
  469. case 2:
  470. return s + " (and 1 other error)"
  471. }
  472. return fmt.Sprintf("%s (and %d other errors)", s, len(e)-1)
  473. }
  474. func (e MultiError) merge(errors MultiError) {
  475. for key, err := range errors {
  476. if e[key] == nil {
  477. e[key] = err
  478. }
  479. }
  480. }