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