binding.go 1.6 KB

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