json_test.go
This file
Path
binding/json_test.go
216 lines · 5.4 KiB · Go
Last changed by
feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
History of this fileTake it
The walk stopped after 200 commits: lines older than cf32d2d point at it.
chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 1–7why, one step back1// Copyright 2019 Gin Core Team. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package binding67import (feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
lines 8–9why, one step back8 "io"9 "net/http/httptest"chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
line 10why, one step back10 "testing"feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
lines 11–12why, one step back11 "time"12 "unsafe"chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
line 13why, one step back13feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
lines 14–17why, one step back14 "github.com/gin-gonic/gin/codec/json"15 "github.com/gin-gonic/gin/render"16 jsoniter "github.com/json-iterator/go"17 "github.com/modern-go/reflect2"chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 18–38why, one step back18 "github.com/stretchr/testify/assert"19 "github.com/stretchr/testify/require"20)2122func TestJSONBindingBindBody(t *testing.T) {23 var s struct {24 Foo string `json:"foo"`25 }26 err := jsonBinding{}.BindBody([]byte(`{"foo": "FOO"}`), &s)27 require.NoError(t, err)28 assert.Equal(t, "FOO", s.Foo)29}3031func TestJSONBindingBindBodyMap(t *testing.T) {32 s := make(map[string]string)33 err := jsonBinding{}.BindBody([]byte(`{"foo": "FOO","hello":"world"}`), &s)34 require.NoError(t, err)35 assert.Len(t, s, 2)36 assert.Equal(t, "FOO", s["foo"])37 assert.Equal(t, "world", s["hello"])38}feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
lines 39–216why, one step back3940func TestCustomJsonCodec(t *testing.T) {41 // Restore json encoding configuration after testing42 oldMarshal := json.API43 defer func() {44 json.API = oldMarshal45 }()46 // Custom json api47 json.API = customJsonApi{}4849 // test decode json50 obj := customReq{}51 err := jsonBinding{}.BindBody([]byte(`{"time_empty":null,"time_struct": "2001-12-05 10:01:02.345","time_nil":null,"time_pointer":"2002-12-05 10:01:02.345"}`), &obj)52 require.NoError(t, err)53 assert.Equal(t, zeroTime, obj.TimeEmpty)54 assert.Equal(t, time.Date(2001, 12, 5, 10, 1, 2, 345000000, time.Local), obj.TimeStruct)55 assert.Nil(t, obj.TimeNil)56 assert.Equal(t, time.Date(2002, 12, 5, 10, 1, 2, 345000000, time.Local), *obj.TimePointer)57 // test encode json58 w := httptest.NewRecorder()59 err2 := (render.PureJSON{Data: obj}).Render(w)60 require.NoError(t, err2)61 assert.JSONEq(t, "{\"time_empty\":null,\"time_struct\":\"2001-12-05 10:01:02.345\",\"time_nil\":null,\"time_pointer\":\"2002-12-05 10:01:02.345\"}\n", w.Body.String())62 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))63}6465type customReq struct {66 TimeEmpty time.Time `json:"time_empty"`67 TimeStruct time.Time `json:"time_struct"`68 TimeNil *time.Time `json:"time_nil"`69 TimePointer *time.Time `json:"time_pointer"`70}7172var customConfig = jsoniter.Config{73 EscapeHTML: true,74 SortMapKeys: true,75 ValidateJsonRawMessage: true,76}.Froze()7778func init() {79 customConfig.RegisterExtension(&TimeEx{})80 customConfig.RegisterExtension(&TimePointerEx{})81}8283type customJsonApi struct{}8485func (j customJsonApi) Marshal(v any) ([]byte, error) {86 return customConfig.Marshal(v)87}8889func (j customJsonApi) Unmarshal(data []byte, v any) error {90 return customConfig.Unmarshal(data, v)91}9293func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {94 return customConfig.MarshalIndent(v, prefix, indent)95}9697func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {98 return customConfig.NewEncoder(writer)99}100101func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {102 return customConfig.NewDecoder(reader)103}104105// region Time Extension106107var (108 zeroTime = time.Time{}109 timeType = reflect2.TypeOfPtr((*time.Time)(nil)).Elem()110 defaultTimeCodec = &timeCodec{}111)112113type TimeEx struct {114 jsoniter.DummyExtension115}116117func (te *TimeEx) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {118 if typ == timeType {119 return defaultTimeCodec120 }121 return nil122}123124func (te *TimeEx) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {125 if typ == timeType {126 return defaultTimeCodec127 }128 return nil129}130131type timeCodec struct{}132133func (tc timeCodec) IsEmpty(ptr unsafe.Pointer) bool {134 t := *((*time.Time)(ptr))135 return t.Equal(zeroTime)136}137138func (tc timeCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {139 t := *((*time.Time)(ptr))140 if t.Equal(zeroTime) {141 stream.WriteNil()142 return143 }144 stream.WriteString(t.In(time.Local).Format("2006-01-02 15:04:05.000"))145}146147func (tc timeCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {148 ts := iter.ReadString()149 if len(ts) == 0 {150 *((*time.Time)(ptr)) = zeroTime151 return152 }153 t, err := time.ParseInLocation("2006-01-02 15:04:05.000", ts, time.Local)154 if err != nil {155 panic(err)156 }157 *((*time.Time)(ptr)) = t158}159160// endregion161162// region *Time Extension163164var (165 timePointerType = reflect2.TypeOfPtr((**time.Time)(nil)).Elem()166 defaultTimePointerCodec = &timePointerCodec{}167)168169type TimePointerEx struct {170 jsoniter.DummyExtension171}172173func (tpe *TimePointerEx) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {174 if typ == timePointerType {175 return defaultTimePointerCodec176 }177 return nil178}179180func (tpe *TimePointerEx) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {181 if typ == timePointerType {182 return defaultTimePointerCodec183 }184 return nil185}186187type timePointerCodec struct{}188189func (tpc timePointerCodec) IsEmpty(ptr unsafe.Pointer) bool {190 t := *((**time.Time)(ptr))191 return t == nil || (*t).Equal(zeroTime)192}193194func (tpc timePointerCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {195 t := *((**time.Time)(ptr))196 if t == nil || (*t).Equal(zeroTime) {197 stream.WriteNil()198 return199 }200 stream.WriteString(t.In(time.Local).Format("2006-01-02 15:04:05.000"))201}202203func (tpc timePointerCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {204 ts := iter.ReadString()205 if len(ts) == 0 {206 *((**time.Time)(ptr)) = nil207 return208 }209 t, err := time.ParseInLocation("2006-01-02 15:04:05.000", ts, time.Local)210 if err != nil {211 panic(err)212 }213 *((**time.Time)(ptr)) = &t214}215216// endregion