binding.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. )
  16. type Binding interface {
  17. Name() string
  18. Bind(*http.Request, interface{}) error
  19. }
  20. type StructValidator interface {
  21. // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
  22. // If the received type is not a struct, any validation should be skipped and nil must be returned.
  23. // If the received type is a struct or pointer to a struct, the validation should be performed.
  24. // If the struct is not valid or the validation itself fails, a descriptive error should be returned.
  25. // Otherwise nil must be returned.
  26. ValidateStruct(interface{}) error
  27. }
  28. var Validator StructValidator = &defaultValidator{}
  29. var (
  30. JSON = jsonBinding{}
  31. XML = xmlBinding{}
  32. Form = formBinding{}
  33. FormPost = formPostBinding{}
  34. FormMultipart = formMultipartBinding{}
  35. ProtoBuf = protobufBinding{}
  36. )
  37. func Default(method, contentType string) Binding {
  38. if method == "GET" {
  39. return Form
  40. } else {
  41. switch contentType {
  42. case MIMEJSON:
  43. return JSON
  44. case MIMEXML, MIMEXML2:
  45. return XML
  46. case MIMEPROTOBUF:
  47. return ProtoBuf
  48. default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
  49. return Form
  50. }
  51. }
  52. }
  53. func validate(obj interface{}) error {
  54. if Validator == nil {
  55. return nil
  56. }
  57. return Validator.ValidateStruct(obj)
  58. }