json.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. //"github.com/gin-gonic/gin/internal/json"
  12. )
  13. // EnableDecoderUseNumber is used to call the UseNumber method on the JSON
  14. // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
  15. // interface{} as a Number instead of as a float64.
  16. var EnableDecoderUseNumber = false
  17. type jsonBinding struct{}
  18. func (jsonBinding) Name() string {
  19. return "json"
  20. }
  21. func (jsonBinding) Bind(req *http.Request, obj interface{}) error {
  22. if req == nil || req.Body == nil {
  23. return fmt.Errorf("invalid request")
  24. }
  25. return decodeJSON(req.Body, obj)
  26. }
  27. func (jsonBinding) BindBody(body []byte, obj interface{}) error {
  28. return decodeJSON(bytes.NewReader(body), obj)
  29. }
  30. func decodeJSON(r io.Reader, obj interface{}) error {
  31. decoder := json.NewDecoder(r)
  32. if EnableDecoderUseNumber {
  33. decoder.UseNumber()
  34. }
  35. if err := decoder.Decode(obj); err != nil {
  36. return err
  37. }
  38. return validate(obj)
  39. }