decoder.go 15 KB

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