decoder.go 14 KB

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