binding.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. FormPost = formPostBinding{}
  36. FormMultipart = formMultipartBinding{}
  37. ProtoBuf = protobufBinding{}
  38. MsgPack = msgpackBinding{}
  39. )
  40. func Default(method, contentType string) Binding {
  41. if method == "GET" {
  42. return Form
  43. }
  44. switch contentType {
  45. case MIMEJSON:
  46. return JSON
  47. case MIMEXML, MIMEXML2:
  48. return XML
  49. case MIMEPROTOBUF:
  50. return ProtoBuf
  51. case MIMEMSGPACK, MIMEMSGPACK2:
  52. return MsgPack
  53. default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
  54. return Form
  55. }
  56. }
  57. func validate(obj interface{}) error {
  58. if Validator == nil {
  59. return nil
  60. }
  61. return Validator.ValidateStruct(obj)
  62. }