json.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. "fmt"
  8. "io"
  9. "net/http"
  10. "encoding/json"
  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. type jsonBinding struct{}
  17. func (jsonBinding) Name() string {
  18. return "json"
  19. }
  20. func (jsonBinding) Bind(req *http.Request, obj interface{}) error {
  21. if req == nil || req.Body == nil {
  22. return fmt.Errorf("invalid request")
  23. }
  24. return decodeJSON(req.Body, obj)
  25. }
  26. func (jsonBinding) BindBody(body []byte, obj interface{}) error {
  27. return decodeJSON(bytes.NewReader(body), obj)
  28. }
  29. func decodeJSON(r io.Reader, obj interface{}) error {
  30. decoder := json.NewDecoder(r)
  31. if EnableDecoderUseNumber {
  32. decoder.UseNumber()
  33. }
  34. if err := decoder.Decode(obj); err != nil {
  35. return err
  36. }
  37. return validate(obj)
  38. }