From fb7448f081196b9c86cade4f58b663cab2207025 Mon Sep 17 00:00:00 2001 From: whirosan Date: Mon, 10 Jul 2017 17:33:35 +0900 Subject: [PATCH] feat(binding): add UseNumber() in gin.Context.BindJSON() (#997) close #368 * resolve #368 add option to UseNumber() in gin.Context.BindJSON() * add test --- binding/json.go | 8 +++++++- mode.go | 4 ++++ mode_test.go | 7 +++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/binding/json.go b/binding/json.go index 20aae8cf..215fa9bf 100644 --- a/binding/json.go +++ b/binding/json.go @@ -10,7 +10,10 @@ import ( "github.com/json-iterator/go" ) -var json = jsoniter.ConfigCompatibleWithStandardLibrary +var ( + json = jsoniter.ConfigCompatibleWithStandardLibrary + EnableDecoderUseNumber = false +) type jsonBinding struct{} @@ -20,6 +23,9 @@ func (jsonBinding) Name() string { func (jsonBinding) Bind(req *http.Request, obj interface{}) error { decoder := json.NewDecoder(req.Body) + if EnableDecoderUseNumber { + decoder.UseNumber() + } if err := decoder.Decode(obj); err != nil { return err } diff --git a/mode.go b/mode.go index e24dbdc2..b0d2c27d 100644 --- a/mode.go +++ b/mode.go @@ -64,6 +64,10 @@ func DisableBindValidation() { binding.Validator = nil } +func EnableJsonDecoderUseNumber() { + binding.EnableDecoderUseNumber = true +} + func Mode() string { return modeName } diff --git a/mode_test.go b/mode_test.go index 0a9cbc3c..f3b88a12 100644 --- a/mode_test.go +++ b/mode_test.go @@ -8,6 +8,7 @@ import ( "os" "testing" + "github.com/gin-gonic/gin/binding" "github.com/stretchr/testify/assert" ) @@ -34,3 +35,9 @@ func TestSetMode(t *testing.T) { assert.Panics(t, func() { SetMode("unknown") }) } + +func TestEnableJsonDecoderUseNumber(t *testing.T) { + assert.False(t, binding.EnableDecoderUseNumber) + EnableJsonDecoderUseNumber() + assert.True(t, binding.EnableDecoderUseNumber) +}