binding.go 2.4 KB

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