binding.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 (
  6. "net/http"
  7. "reflect"
  8. "gopkg.in/bluesuncorp/validator.v5"
  9. )
  10. const (
  11. MIMEJSON = "application/json"
  12. MIMEHTML = "text/html"
  13. MIMEXML = "application/xml"
  14. MIMEXML2 = "text/xml"
  15. MIMEPlain = "text/plain"
  16. MIMEPOSTForm = "application/x-www-form-urlencoded"
  17. MIMEMultipartPOSTForm = "multipart/form-data"
  18. )
  19. type Binding interface {
  20. Name() string
  21. Bind(*http.Request, interface{}) error
  22. }
  23. var validate = validator.New("binding", validator.BakedInValidators)
  24. var (
  25. JSON = jsonBinding{}
  26. XML = xmlBinding{}
  27. Form = formBinding{}
  28. )
  29. func Default(method, contentType string) Binding {
  30. if method == "GET" {
  31. return Form
  32. } else {
  33. switch contentType {
  34. case MIMEJSON:
  35. return JSON
  36. case MIMEXML, MIMEXML2:
  37. return XML
  38. default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
  39. return Form
  40. }
  41. }
  42. }
  43. func ValidateField(f interface{}, tag string) error {
  44. if err := validate.Field(f, tag); err != nil {
  45. return error(err)
  46. }
  47. return nil
  48. }
  49. func Validate(obj interface{}) error {
  50. if kindOfData(obj) != reflect.Struct {
  51. return nil
  52. }
  53. if err := validate.Struct(obj); err != nil {
  54. return error(err)
  55. }
  56. return nil
  57. }
  58. func kindOfData(data interface{}) reflect.Kind {
  59. value := reflect.ValueOf(data)
  60. valueType := value.Kind()
  61. if valueType == reflect.Ptr {
  62. valueType = value.Elem().Kind()
  63. }
  64. return valueType
  65. }