feat: support custom json codec at runtime (#3391)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor(json): export json codec * feat(json): support custom json codec at runtime * chore(copyright): update copyright to 2025 gin core team * docs(gin): add custom json codec examples in doc file
authored by Tim · committed by GitHub · parent 0a86488 · Browse files · 19 files·+497 added−125 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+497 added−125 removed
- other:+497 added−125 removed
Provenance
- Commit
688a429- Tree
29b4458- Author
Tim <xuchonglei@126.com>- Committer
GitHub <noreply@github.com>- Parent
0a86488
19 files changed+497 added−125 removed
modified:binding/form_mapping.go+3 added-3 removed
11 unmodified lines12 "strconv"13 "strings"14 "time"15 16+ "github.com/gin-gonic/gin/codec/json"17 "github.com/gin-gonic/gin/internal/bytesconv"17- "github.com/gin-gonic/gin/internal/json"18 )19 20 var (21 errUnknownType = errors.New("unknown type")310 unmodified lines332 return setTimeField(val, field, value)333 case multipart.FileHeader:334 return nil335 }336- return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface())336+ return json.API.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface())337 case reflect.Map:338- return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface())338+ return json.API.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface())339 case reflect.Ptr:340 if !value.Elem().IsValid() {341 value.Set(reflect.New(value.Type().Elem()))342 }166 unmodified linesmodified:binding/json_test.go+186 added
3 unmodified lines4 5 package binding6 7 import (8+ "io"9+ "net/http/httptest"10 "testing"11+ "time"12+ "unsafe"13 14+ "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"18 "github.com/stretchr/testify/assert"19 "github.com/stretchr/testify/require"20 )21 13 unmodified lines35 assert.Len(t, s, 2)36 assert.Equal(t, "FOO", s["foo"])37 assert.Equal(t, "world", s["hello"])38 }39+40+func 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{}48+49+ // 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+}64+65+type 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+}71+72+var customConfig = jsoniter.Config{73+ EscapeHTML: true,74+ SortMapKeys: true,75+ ValidateJsonRawMessage: true,76+}.Froze()77+78+func init() {79+ customConfig.RegisterExtension(&TimeEx{})80+ customConfig.RegisterExtension(&TimePointerEx{})81+}82+83+type customJsonApi struct{}84+85+func (j customJsonApi) Marshal(v any) ([]byte, error) {86+ return customConfig.Marshal(v)87+}88+89+func (j customJsonApi) Unmarshal(data []byte, v any) error {90+ return customConfig.Unmarshal(data, v)91+}92+93+func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {94+ return customConfig.MarshalIndent(v, prefix, indent)95+}96+97+func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {98+ return customConfig.NewEncoder(writer)99+}100+101+func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {102+ return customConfig.NewDecoder(reader)103+}104+105+// region Time Extension106+107+var (108+ zeroTime = time.Time{}109+ timeType = reflect2.TypeOfPtr((*time.Time)(nil)).Elem()110+ defaultTimeCodec = &timeCodec{}111+)112+113+type TimeEx struct {114+ jsoniter.DummyExtension115+}116+117+func (te *TimeEx) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {118+ if typ == timeType {119+ return defaultTimeCodec120+ }121+ return nil122+}123+124+func (te *TimeEx) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {125+ if typ == timeType {126+ return defaultTimeCodec127+ }128+ return nil129+}130+131+type timeCodec struct{}132+133+func (tc timeCodec) IsEmpty(ptr unsafe.Pointer) bool {134+ t := *((*time.Time)(ptr))135+ return t.Equal(zeroTime)136+}137+138+func (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+}146+147+func (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+}159+160+// endregion161+162+// region *Time Extension163+164+var (165+ timePointerType = reflect2.TypeOfPtr((**time.Time)(nil)).Elem()166+ defaultTimePointerCodec = &timePointerCodec{}167+)168+169+type TimePointerEx struct {170+ jsoniter.DummyExtension171+}172+173+func (tpe *TimePointerEx) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {174+ if typ == timePointerType {175+ return defaultTimePointerCodec176+ }177+ return nil178+}179+180+func (tpe *TimePointerEx) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {181+ if typ == timePointerType {182+ return defaultTimePointerCodec183+ }184+ return nil185+}186+187+type timePointerCodec struct{}188+189+func (tpc timePointerCodec) IsEmpty(ptr unsafe.Pointer) bool {190+ t := *((**time.Time)(ptr))191+ return t == nil || (*t).Equal(zeroTime)192+}193+194+func (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+}202+203+func (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+}215+216+// endregionmodified:binding/json.go+2 added-2 removed
8 unmodified lines9 "errors"10 "io"11 "net/http"12 13- "github.com/gin-gonic/gin/internal/json"13+ "github.com/gin-gonic/gin/codec/json"14 )15 16 // EnableDecoderUseNumber is used to call the UseNumber method on the JSON17 // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an23 unmodified lines41 return decodeJSON(bytes.NewReader(body), obj)42 }43 44 func decodeJSON(r io.Reader, obj any) error {45- decoder := json.NewDecoder(r)45+ decoder := json.API.NewDecoder(r)46 if EnableDecoderUseNumber {47 decoder.UseNumber()48 }49 if EnableDecoderDisallowUnknownFields {7 unmodified linesadded:codec/json/api.go+57 added
1+// Copyright 2025 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.4+5+package json6+7+import "io"8+9+// API the json codec in use.10+var API Core11+12+// Core the api for json codec.13+type Core interface {14+ Marshal(v any) ([]byte, error)15+ Unmarshal(data []byte, v any) error16+ MarshalIndent(v any, prefix, indent string) ([]byte, error)17+ NewEncoder(writer io.Writer) Encoder18+ NewDecoder(reader io.Reader) Decoder19+}20+21+// Encoder an interface writes JSON values to an output stream.22+type Encoder interface {23+ // SetEscapeHTML specifies whether problematic HTML characters24+ // should be escaped inside JSON quoted strings.25+ // The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e26+ // to avoid certain safety problems that can arise when embedding JSON in HTML.27+ //28+ // In non-HTML settings where the escaping interferes with the readability29+ // of the output, SetEscapeHTML(false) disables this behavior.30+ SetEscapeHTML(on bool)31+32+ // Encode writes the JSON encoding of v to the stream,33+ // followed by a newline character.34+ //35+ // See the documentation for Marshal for details about the36+ // conversion of Go values to JSON.37+ Encode(v any) error38+}39+40+// Decoder an interface reads and decodes JSON values from an input stream.41+type Decoder interface {42+ // UseNumber causes the Decoder to unmarshal a number into an any as a43+ // Number instead of as a float64.44+ UseNumber()45+46+ // DisallowUnknownFields causes the Decoder to return an error when the destination47+ // is a struct and the input contains object keys which do not match any48+ // non-ignored, exported fields in the destination.49+ DisallowUnknownFields()50+51+ // Decode reads the next JSON-encoded value from its52+ // input and stores it in the value pointed to by v.53+ //54+ // See the documentation for Unmarshal for details about55+ // the conversion of JSON into a Go value.56+ Decode(v any) error57+}added:codec/json/go_json.go+42 added
1+// Copyright 2025 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.4+5+//go:build go_json6+7+package json8+9+import (10+ "io"11+12+ "github.com/goccy/go-json"13+)14+15+// Package indicates what library is being used for JSON encoding.16+const Package = "github.com/goccy/go-json"17+18+func init() {19+ API = gojsonApi{}20+}21+22+type gojsonApi struct{}23+24+func (j gojsonApi) Marshal(v any) ([]byte, error) {25+ return json.Marshal(v)26+}27+28+func (j gojsonApi) Unmarshal(data []byte, v any) error {29+ return json.Unmarshal(data, v)30+}31+32+func (j gojsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {33+ return json.MarshalIndent(v, prefix, indent)34+}35+36+func (j gojsonApi) NewEncoder(writer io.Writer) Encoder {37+ return json.NewEncoder(writer)38+}39+40+func (j gojsonApi) NewDecoder(reader io.Reader) Decoder {41+ return json.NewDecoder(reader)42+}added:codec/json/json.go+41 added
1+// Copyright 2025 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.4+5+//go:build !jsoniter && !go_json && !(sonic && (linux || windows || darwin))6+7+package json8+9+import (10+ "encoding/json"11+ "io"12+)13+14+// Package indicates what library is being used for JSON encoding.15+const Package = "encoding/json"16+17+func init() {18+ API = jsonApi{}19+}20+21+type jsonApi struct{}22+23+func (j jsonApi) Marshal(v any) ([]byte, error) {24+ return json.Marshal(v)25+}26+27+func (j jsonApi) Unmarshal(data []byte, v any) error {28+ return json.Unmarshal(data, v)29+}30+31+func (j jsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {32+ return json.MarshalIndent(v, prefix, indent)33+}34+35+func (j jsonApi) NewEncoder(writer io.Writer) Encoder {36+ return json.NewEncoder(writer)37+}38+39+func (j jsonApi) NewDecoder(reader io.Reader) Decoder {40+ return json.NewDecoder(reader)41+}added:codec/json/jsoniter.go+44 added
1+// Copyright 2025 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.4+5+//go:build jsoniter6+7+package json8+9+import (10+ "io"11+12+ jsoniter "github.com/json-iterator/go"13+)14+15+// Package indicates what library is being used for JSON encoding.16+const Package = "github.com/json-iterator/go"17+18+func init() {19+ API = jsoniterApi{}20+}21+22+var json = jsoniter.ConfigCompatibleWithStandardLibrary23+24+type jsoniterApi struct{}25+26+func (j jsoniterApi) Marshal(v any) ([]byte, error) {27+ return json.Marshal(v)28+}29+30+func (j jsoniterApi) Unmarshal(data []byte, v any) error {31+ return json.Unmarshal(data, v)32+}33+34+func (j jsoniterApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {35+ return json.MarshalIndent(v, prefix, indent)36+}37+38+func (j jsoniterApi) NewEncoder(writer io.Writer) Encoder {39+ return json.NewEncoder(writer)40+}41+42+func (j jsoniterApi) NewDecoder(reader io.Reader) Decoder {43+ return json.NewDecoder(reader)44+}added:codec/json/sonic.go+44 added
1+// Copyright 2025 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.4+5+//go:build sonic && (linux || windows || darwin)6+7+package json8+9+import (10+ "io"11+12+ "github.com/bytedance/sonic"13+)14+15+// Package indicates what library is being used for JSON encoding.16+const Package = "github.com/bytedance/sonic"17+18+func init() {19+ API = sonicApi{}20+}21+22+var json = sonic.ConfigStd23+24+type sonicApi struct{}25+26+func (j sonicApi) Marshal(v any) ([]byte, error) {27+ return json.Marshal(v)28+}29+30+func (j sonicApi) Unmarshal(data []byte, v any) error {31+ return json.Unmarshal(data, v)32+}33+34+func (j sonicApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {35+ return json.MarshalIndent(v, prefix, indent)36+}37+38+func (j sonicApi) NewEncoder(writer io.Writer) Encoder {39+ return json.NewEncoder(writer)40+}41+42+func (j sonicApi) NewDecoder(reader io.Reader) Decoder {43+ return json.NewDecoder(reader)44+}modified:docs/doc.md+60 added
61 unmodified lines62 - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)63 - [http2 server push](#http2-server-push)64 - [Define format for the log of routes](#define-format-for-the-log-of-routes)65 - [Set and get a cookie](#set-and-get-a-cookie)66+ - [Custom json codec at runtime](#custom-json-codec-at-runtime)67 - [Don't trust all proxies](#dont-trust-all-proxies)68 - [Testing](#testing)69 70 ## Build tags2300 unmodified lines2371 router.Run()2372 }2373 ```2374 2375+### Custom json codec at runtime2376+2377+Gin support custom json serialization and deserialization logic without using compile tags.2378+2379+1. Define a custom struct implements the `json.Core` interface.2380+2381+2. Before your engine starts, assign values to `json.API` using the custom struct.2382+2383+```go2384+package main2385+2386+import (2387+ "io"2388+2389+ "github.com/gin-gonic/gin"2390+ "github.com/gin-gonic/gin/codec/json"2391+ jsoniter "github.com/json-iterator/go"2392+)2393+2394+var customConfig = jsoniter.Config{2395+ EscapeHTML: true,2396+ SortMapKeys: true,2397+ ValidateJsonRawMessage: true,2398+}.Froze()2399+2400+// implement api.JsonApi2401+type customJsonApi struct {2402+}2403+2404+func (j customJsonApi) Marshal(v any) ([]byte, error) {2405+ return customConfig.Marshal(v)2406+}2407+2408+func (j customJsonApi) Unmarshal(data []byte, v any) error {2409+ return customConfig.Unmarshal(data, v)2410+}2411+2412+func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {2413+ return customConfig.MarshalIndent(v, prefix, indent)2414+}2415+2416+func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {2417+ return customConfig.NewEncoder(writer)2418+}2419+2420+func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {2421+ return customConfig.NewDecoder(reader)2422+}2423+2424+func main() {2425+ //Replace the default json api2426+ json.API = customJsonApi{}2427+2428+ //Start your gin engine2429+ router := gin.Default()2430+ router.Run(":8080")2431+}2432+```2433+2434 ## Don't trust all proxies2435 2436 Gin lets you specify which headers to hold the real client IP (if any),2437 as well as specifying which proxies (or direct clients) you trust to120 unmodified linesdeleted:internal/json/go_json.go-25 removed
1-// Copyright 2017 Bo-Yi Wu. All rights reserved.2-// Use of this source code is governed by a MIT style3-// license that can be found in the LICENSE file.4-5-//go:build go_json6-7-package json8-9-import json "github.com/goccy/go-json"10-11-var (12- // Marshal is exported by gin/json package.13- Marshal = json.Marshal14- // Unmarshal is exported by gin/json package.15- Unmarshal = json.Unmarshal16- // MarshalIndent is exported by gin/json package.17- MarshalIndent = json.MarshalIndent18- // NewDecoder is exported by gin/json package.19- NewDecoder = json.NewDecoder20- // NewEncoder is exported by gin/json package.21- NewEncoder = json.NewEncoder22-)23-24-// Package indicates what library is being used for JSON encoding.25-const Package = "github.com/goccy/go-json"deleted:internal/json/json.go-25 removed
1-// Copyright 2017 Bo-Yi Wu. All rights reserved.2-// Use of this source code is governed by a MIT style3-// license that can be found in the LICENSE file.4-5-//go:build !jsoniter && !go_json && !(sonic && (linux || windows || darwin))6-7-package json8-9-import "encoding/json"10-11-var (12- // Marshal is exported by gin/json package.13- Marshal = json.Marshal14- // Unmarshal is exported by gin/json package.15- Unmarshal = json.Unmarshal16- // MarshalIndent is exported by gin/json package.17- MarshalIndent = json.MarshalIndent18- // NewDecoder is exported by gin/json package.19- NewDecoder = json.NewDecoder20- // NewEncoder is exported by gin/json package.21- NewEncoder = json.NewEncoder22-)23-24-// Package indicates what library is being used for JSON encoding.25-const Package = "encoding/json"deleted:internal/json/jsoniter.go-26 removed
1-// Copyright 2017 Bo-Yi Wu. All rights reserved.2-// Use of this source code is governed by a MIT style3-// license that can be found in the LICENSE file.4-5-//go:build jsoniter6-7-package json8-9-import jsoniter "github.com/json-iterator/go"10-11-var (12- json = jsoniter.ConfigCompatibleWithStandardLibrary13- // Marshal is exported by gin/json package.14- Marshal = json.Marshal15- // Unmarshal is exported by gin/json package.16- Unmarshal = json.Unmarshal17- // MarshalIndent is exported by gin/json package.18- MarshalIndent = json.MarshalIndent19- // NewDecoder is exported by gin/json package.20- NewDecoder = json.NewDecoder21- // NewEncoder is exported by gin/json package.22- NewEncoder = json.NewEncoder23-)24-25-// Package indicates what library is being used for JSON encoding.26-const Package = "github.com/json-iterator/go"deleted:internal/json/sonic.go-26 removed
1-// Copyright 2022 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.4-5-//go:build sonic && (linux || windows || darwin)6-7-package json8-9-import "github.com/bytedance/sonic"10-11-var (12- json = sonic.ConfigStd13- // Marshal is exported by gin/json package.14- Marshal = json.Marshal15- // Unmarshal is exported by gin/json package.16- Unmarshal = json.Unmarshal17- // MarshalIndent is exported by gin/json package.18- MarshalIndent = json.MarshalIndent19- // NewDecoder is exported by gin/json package.20- NewDecoder = json.NewDecoder21- // NewEncoder is exported by gin/json package.22- NewEncoder = json.NewEncoder23-)24-25-// Package indicates what library is being used for JSON encoding.26-const Package = "github.com/bytedance/sonic"modified:render/json.go+7 added-7 removed
9 unmodified lines10 "html/template"11 "net/http"12 "unicode"13 14+ "github.com/gin-gonic/gin/codec/json"15 "github.com/gin-gonic/gin/internal/bytesconv"15- "github.com/gin-gonic/gin/internal/json"16 )17 18 // JSON contains the given interface object.19 type JSON struct {45 unmodified lines65 66 // WriteJSON marshals the given interface object and writes it with custom ContentType.67 func WriteJSON(w http.ResponseWriter, obj any) error {68 writeContentType(w, jsonContentType)69- jsonBytes, err := json.Marshal(obj)69+ jsonBytes, err := json.API.Marshal(obj)70 if err != nil {71 return err72 }73 _, err = w.Write(jsonBytes)2 unmodified lines76 77 // Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType.78 func (r IndentedJSON) Render(w http.ResponseWriter) error {79 r.WriteContentType(w)80- jsonBytes, err := json.MarshalIndent(r.Data, "", " ")80+ jsonBytes, err := json.API.MarshalIndent(r.Data, "", " ")81 if err != nil {82 return err83 }84 _, err = w.Write(jsonBytes)7 unmodified lines92 93 // Render (SecureJSON) marshals the given interface object and writes it with custom ContentType.94 func (r SecureJSON) Render(w http.ResponseWriter) error {95 r.WriteContentType(w)96- jsonBytes, err := json.Marshal(r.Data)96+ jsonBytes, err := json.API.Marshal(r.Data)97 if err != nil {98 return err99 }100 // if the jsonBytes is array values14 unmodified lines115 116 // Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType.117 func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {118 r.WriteContentType(w)119- ret, err := json.Marshal(r.Data)119+ ret, err := json.API.Marshal(r.Data)120 if err != nil {121 return err122 }123 29 unmodified lines153 154 // Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType.155 func (r AsciiJSON) Render(w http.ResponseWriter) error {156 r.WriteContentType(w)157- ret, err := json.Marshal(r.Data)157+ ret, err := json.API.Marshal(r.Data)158 if err != nil {159 return err160 }161 20 unmodified lines182 183 // Render (PureJSON) writes custom ContentType and encodes the given interface object.184 func (r PureJSON) Render(w http.ResponseWriter) error {185 r.WriteContentType(w)186- encoder := json.NewEncoder(w)186+ encoder := json.API.NewEncoder(w)187 encoder.SetEscapeHTML(false)188 return encoder.Encode(r.Data)189 }190 4 unmodified linesmodified:render/render_test.go+2 added-2 removed
13 unmodified lines14 "strconv"15 "strings"16 "testing"17 18- "github.com/gin-gonic/gin/internal/json"18+ "github.com/gin-gonic/gin/codec/json"19 testdata "github.com/gin-gonic/gin/testdata/protoexample"20 "github.com/stretchr/testify/assert"21 "github.com/stretchr/testify/require"22 "google.golang.org/protobuf/proto"149 unmodified lines172 ew.bufString = `(`173 err = jsonpJSON.Render(ew)174 assert.Equal(t, `write "`+`(`+`" error`, err.Error())175 176- data, _ := json.Marshal(jsonpJSON.Data) // error was returned while writing data176+ data, _ := json.API.Marshal(jsonpJSON.Data) // error was returned while writing data177 ew.bufString = string(data)178 err = jsonpJSON.Render(ew)179 assert.Equal(t, `write "`+string(data)+`" error`, err.Error())180 441 unmodified linesmodified:context_test.go+1 added-1 removed
26 unmodified lines27 "time"28 29 "github.com/gin-contrib/sse"30 "github.com/gin-gonic/gin/binding"31- "github.com/gin-gonic/gin/internal/json"31+ "github.com/gin-gonic/gin/codec/json"32 testdata "github.com/gin-gonic/gin/testdata/protoexample"33 "github.com/stretchr/testify/assert"34 "github.com/stretchr/testify/require"35 "google.golang.org/protobuf/proto"3291 unmodified linesmodified:errors_test.go+4 added-4 removed
7 unmodified lines8 "errors"9 "fmt"10 "testing"11 12- "github.com/gin-gonic/gin/internal/json"12+ "github.com/gin-gonic/gin/codec/json"13 "github.com/stretchr/testify/assert"14 "github.com/stretchr/testify/require"15 )16 15 unmodified lines32 "error": baseError.Error(),33 "meta": "some data",34 }, err.JSON())35 36- jsonBytes, _ := json.Marshal(err)36+ jsonBytes, _ := json.API.Marshal(err)37 assert.JSONEq(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))38 39 err.SetMeta(H{ //nolint: errcheck40 "status": "200",50 unmodified lines91 H{"error": "first"},92 H{"error": "second", "meta": "some data"},93 H{"error": "third", "status": "400"},94 }, errs.JSON())95- jsonBytes, _ := json.Marshal(errs)95+ jsonBytes, _ := json.API.Marshal(errs)96 assert.JSONEq(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes))97 errs = errorMsgs{98 {Err: errors.New("first"), Type: ErrorTypePrivate},99 }100 assert.Equal(t, H{"error": "first"}, errs.JSON())101- jsonBytes, _ = json.Marshal(errs)101+ jsonBytes, _ = json.API.Marshal(errs)102 assert.JSONEq(t, "{\"error\":\"first\"}", string(jsonBytes))103 104 errs = errorMsgs{}105 assert.Nil(t, errs.Last())35 unmodified linesmodified:errors.go+3 added-3 removed
7 unmodified lines8 "fmt"9 "reflect"10 "strings"11 12- "github.com/gin-gonic/gin/internal/json"12+ "github.com/gin-gonic/gin/codec/json"13 )14 15 // ErrorType is an unsigned 64-bit error code as defined in the gin spec.16 type ErrorType uint6459 unmodified lines76 }77 78 // MarshalJSON implements the json.Marshaller interface.79 func (msg *Error) MarshalJSON() ([]byte, error) {80- return json.Marshal(msg.JSON())80+ return json.API.Marshal(msg.JSON())81 }82 83 // Error implements the error interface.84 func (msg Error) Error() string {71 unmodified lines156 }157 158 // MarshalJSON implements the json.Marshaller interface.159 func (a errorMsgs) MarshalJSON() ([]byte, error) {160- return json.Marshal(a.JSON())160+ return json.API.Marshal(a.JSON())161 }162 163 func (a errorMsgs) String() string {164 if len(a) == 0 {11 unmodified linesmodified:go.mod+1 added-1 removed
7 unmodified lines8 github.com/go-playground/validator/v10 v10.26.09 github.com/goccy/go-json v0.10.210 github.com/json-iterator/go v1.1.1211 github.com/mattn/go-isatty v0.0.2012+ github.com/modern-go/reflect2 v1.0.213 github.com/pelletier/go-toml/v2 v2.2.414 github.com/quic-go/quic-go v0.52.015 github.com/stretchr/testify v1.10.016 github.com/ugorji/go/codec v1.2.1213 unmodified lines30 github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect31 github.com/klauspost/cpuid/v2 v2.0.9 // indirect32 github.com/leodido/go-urn v1.4.0 // indirect33 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect33- github.com/modern-go/reflect2 v1.0.2 // indirect34 github.com/onsi/ginkgo/v2 v2.9.5 // indirect35 github.com/pmezard/go-difflib v1.0.0 // indirect36 github.com/quic-go/qpack v0.5.1 // indirect37 github.com/twitchyliquid64/golang-asm v0.15.1 // indirect9 unmodified lines