binding.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/joeybloggs/go-validate-yourself.v4"
  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 _validator = validator.NewValidator("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:
  38. return Form
  39. }
  40. }
  41. }
  42. func Validate(obj interface{}) error {
  43. if err := _validator.ValidateStruct(obj); err != nil {
  44. return error(err)
  45. }
  46. return nil
  47. }