binding.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. XML = xmlBinding{}
  25. JSON = jsonBinding{}
  26. Form = formBinding{}
  27. MultipartForm = multipartFormBinding{}
  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. case MIMEMultipartPOSTForm:
  39. return MultipartForm
  40. default:
  41. return Form
  42. }
  43. }
  44. }
  45. func ValidateField(f interface{}, tag string) error {
  46. if err := validate.Field(f, tag); err != nil {
  47. return error(err)
  48. }
  49. return nil
  50. }
  51. func Validate(obj interface{}) error {
  52. if err := validate.Struct(obj); err != nil {
  53. return error(err)
  54. }
  55. return nil
  56. }