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