binding.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package binding
  2. import (
  3. "net/http"
  4. "strings"
  5. "gopkg.in/go-playground/validator.v9"
  6. )
  7. // MIME
  8. const (
  9. MIMEJSON = "application/json"
  10. MIMEHTML = "text/html"
  11. MIMEXML = "application/xml"
  12. MIMEXML2 = "text/xml"
  13. MIMEPlain = "text/plain"
  14. MIMEPOSTForm = "application/x-www-form-urlencoded"
  15. MIMEMultipartPOSTForm = "multipart/form-data"
  16. )
  17. // Binding http binding request interface.
  18. type Binding interface {
  19. Name() string
  20. Bind(*http.Request, interface{}) error
  21. }
  22. // StructValidator http validator interface.
  23. type StructValidator interface {
  24. // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
  25. // If the received type is not a struct, any validation should be skipped and nil must be returned.
  26. // If the received type is a struct or pointer to a struct, the validation should be performed.
  27. // If the struct is not valid or the validation itself fails, a descriptive error should be returned.
  28. // Otherwise nil must be returned.
  29. ValidateStruct(interface{}) error
  30. // RegisterValidation adds a validation Func to a Validate's map of validators denoted by the key
  31. // NOTE: if the key already exists, the previous validation function will be replaced.
  32. // NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation
  33. RegisterValidation(string, validator.Func) error
  34. }
  35. // Validator default validator.
  36. var Validator StructValidator = &defaultValidator{}
  37. // Binding
  38. var (
  39. JSON = jsonBinding{}
  40. XML = xmlBinding{}
  41. Form = formBinding{}
  42. Query = queryBinding{}
  43. FormPost = formPostBinding{}
  44. FormMultipart = formMultipartBinding{}
  45. )
  46. // Default get by binding type by method and contexttype.
  47. func Default(method, contentType string) Binding {
  48. if method == "GET" {
  49. return Form
  50. }
  51. contentType = stripContentTypeParam(contentType)
  52. switch contentType {
  53. case MIMEJSON:
  54. return JSON
  55. case MIMEXML, MIMEXML2:
  56. return XML
  57. default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
  58. return Form
  59. }
  60. }
  61. func validate(obj interface{}) error {
  62. if Validator == nil {
  63. return nil
  64. }
  65. return Validator.ValidateStruct(obj)
  66. }
  67. func stripContentTypeParam(contentType string) string {
  68. i := strings.Index(contentType, ";")
  69. if i != -1 {
  70. contentType = contentType[:i]
  71. }
  72. return contentType
  73. }