json.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. )
  12. // EnableDecoderUseNumber is used to call the UseNumber method on the JSON
  13. // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
  14. // interface{} as a Number instead of as a float64.
  15. var EnableDecoderUseNumber = false
  16. // EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method
  17. // on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to
  18. // return an error when the destination is a struct and the input contains object
  19. // keys which do not match any non-ignored, exported fields in the destination.
  20. var EnableDecoderDisallowUnknownFields = false
  21. type jsonBinding struct{}
  22. func (jsonBinding) Name() string {
  23. return "json"
  24. }
  25. func (jsonBinding) Bind(req *http.Request, obj interface{}) error {
  26. if req == nil || req.Body == nil {
  27. return fmt.Errorf("invalid request")
  28. }
  29. return decodeJSON(req.Body, obj)
  30. }
  31. func (jsonBinding) BindBody(body []byte, obj interface{}) error {
  32. return decodeJSON(bytes.NewReader(body), obj)
  33. }
  34. func decodeJSON(r io.Reader, obj interface{}) error {
  35. decoder := json.NewDecoder(r)
  36. if EnableDecoderUseNumber {
  37. decoder.UseNumber()
  38. }
  39. if EnableDecoderDisallowUnknownFields {
  40. decoder.DisallowUnknownFields()
  41. }
  42. if err := decoder.Decode(obj); err != nil {
  43. return err
  44. }
  45. return validate(obj)
  46. }