schema.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package schema
  2. var (
  3. defaultDecoder = NewDecoder() // form, url, header, param, schema.
  4. // Form Decoder. The default instance for DecodeForm function.
  5. Form = NewDecoder().SetAliasTag("form")
  6. // Query Decoder. The default instance for DecodeQuery function.
  7. Query = NewDecoder().SetAliasTag("url").IgnoreUnknownKeys(true) // allow unknown url queries
  8. // Headers Decoder. The default instance for DecodeHeaders function.
  9. Headers = NewDecoder().SetAliasTag("header").IgnoreUnknownKeys(true)
  10. // Params Decoder. The default instance for DecodeParams function.
  11. Params = NewDecoder().SetAliasTag("param").IgnoreUnknownKeys(true)
  12. )
  13. // Decode maps "values" to "ptr".
  14. // With one of the "form", "url" or "schema" tag fields that can override the field's name mapping to key.
  15. func Decode(values map[string][]string, ptr interface{}) error {
  16. return defaultDecoder.Decode(ptr, values)
  17. }
  18. // DecodeForm maps "values" to "ptr".
  19. // With "form" tag for fields.
  20. func DecodeForm(values map[string][]string, ptr interface{}) error {
  21. return Form.Decode(ptr, values)
  22. }
  23. // DecodeQuery maps "values" to "ptr".
  24. // With "url" tag for fields.
  25. func DecodeQuery(values map[string][]string, ptr interface{}) error {
  26. return Query.Decode(ptr, values)
  27. }
  28. // DecodeHeaders maps "values" to "ptr".
  29. // With "header" tag for fields.
  30. func DecodeHeaders(values map[string][]string, ptr interface{}) error {
  31. return Headers.Decode(ptr, values)
  32. }
  33. // DecodeParams maps "values" to "ptr".
  34. // With "param" tag for fields.
  35. func DecodeParams(values map[string][]string, ptr interface{}) error {
  36. return Params.Decode(ptr, values)
  37. }
  38. // IsErrPath reports whether the incoming error is type of unknown field passed,
  39. // which can be ignored when server allows unknown post values to be sent by the client.
  40. func IsErrPath(err error) bool {
  41. if err == nil {
  42. return false
  43. }
  44. if m, ok := err.(MultiError); ok {
  45. j := len(m)
  46. for _, e := range m {
  47. if _, is := e.(UnknownKeyError); is {
  48. j--
  49. }
  50. }
  51. return j == 0
  52. }
  53. return false
  54. }