binding.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. FormPost = formPostBinding{}
  33. FormMultipart = formMultipartBinding{}
  34. )
  35. func Default(method, contentType string) Binding {
  36. if method == "GET" {
  37. return Form
  38. } else {
  39. switch contentType {
  40. case MIMEJSON:
  41. return JSON
  42. case MIMEXML, MIMEXML2:
  43. return XML
  44. default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
  45. return Form
  46. }
  47. }
  48. }
  49. func validate(obj interface{}) error {
  50. if Validator == nil {
  51. return nil
  52. }
  53. return Validator.ValidateStruct(obj)
  54. }