binding.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 "net/http"
  6. const (
  7. MIMEJSON = "application/json"
  8. MIMEHTML = "text/html"
  9. MIMEXML = "application/xml"
  10. MIMEXML2 = "text/xml"
  11. MIMEPlain = "text/plain"
  12. MIMEPOSTForm = "application/x-www-form-urlencoded"
  13. MIMEMultipartPOSTForm = "multipart/form-data"
  14. MIMEPROTOBUF = "application/x-protobuf"
  15. MIMEMSGPACK = "application/x-msgpack"
  16. MIMEMSGPACK2 = "application/msgpack"
  17. )
  18. type Binding interface {
  19. Name() string
  20. Bind(*http.Request, interface{}) error
  21. }
  22. type StructValidator interface {
  23. // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
  24. // If the received type is not a struct, any validation should be skipped and nil must be returned.
  25. // If the received type is a struct or pointer to a struct, the validation should be performed.
  26. // If the struct is not valid or the validation itself fails, a descriptive error should be returned.
  27. // Otherwise nil must be returned.
  28. ValidateStruct(interface{}) error
  29. }
  30. var Validator StructValidator = &defaultValidator{}
  31. var (
  32. JSON = jsonBinding{}
  33. XML = xmlBinding{}
  34. Form = formBinding{}
  35. Query = queryBinding{}
  36. FormPost = formPostBinding{}
  37. FormMultipart = formMultipartBinding{}
  38. ProtoBuf = protobufBinding{}
  39. MsgPack = msgpackBinding{}
  40. )
  41. func Default(method, contentType string) Binding {
  42. if method == "GET" {
  43. return Form
  44. }
  45. switch contentType {
  46. case MIMEJSON:
  47. return JSON
  48. case MIMEXML, MIMEXML2:
  49. return XML
  50. case MIMEPROTOBUF:
  51. return ProtoBuf
  52. case MIMEMSGPACK, MIMEMSGPACK2:
  53. return MsgPack
  54. default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
  55. return Form
  56. }
  57. }
  58. func validate(obj interface{}) error {
  59. if Validator == nil {
  60. return nil
  61. }
  62. return Validator.ValidateStruct(obj)
  63. }