Skip to content
Myr

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

19 files+497 added−125 removed

modified:binding/form_mapping.go+3 added-3 removed
11 unmodified lines
12 "strconv"13 "strings"14 "time"1516 "github.com/gin-gonic/gin/codec/json"17 "github.com/gin-gonic/gin/internal/bytesconv"17 "github.com/gin-gonic/gin/internal/json"18)1920var (21 errUnknownType = errors.New("unknown type")
310 unmodified lines
332 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 lines
modified:binding/json_test.go+186 added
3 unmodified lines
45package binding67import (8 "io"9 "net/http/httptest"10 "testing"11 "time"12 "unsafe"1314 "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 lines
35 assert.Len(t, s, 2)36 assert.Equal(t, "FOO", s["foo"])37 assert.Equal(t, "world", s["hello"])38}3940func 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
modified:binding/json.go+2 added-2 removed
8 unmodified lines
9 "errors"10 "io"11 "net/http"1213 "github.com/gin-gonic/gin/internal/json"13 "github.com/gin-gonic/gin/codec/json"14)1516// EnableDecoderUseNumber is used to call the UseNumber method on the JSON17// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
23 unmodified lines
41 return decodeJSON(bytes.NewReader(body), obj)42}4344func 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 lines
added: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.45package json67import "io"89// API the json codec in use.10var API Core1112// Core the api for json codec.13type 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}2021// Encoder an interface writes JSON values to an output stream.22type 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)3132 // 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}3940// Decoder an interface reads and decodes JSON values from an input stream.41type Decoder interface {42 // UseNumber causes the Decoder to unmarshal a number into an any as a43 // Number instead of as a float64.44 UseNumber()4546 // 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()5051 // 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.45//go:build go_json67package json89import (10 "io"1112 "github.com/goccy/go-json"13)1415// Package indicates what library is being used for JSON encoding.16const Package = "github.com/goccy/go-json"1718func init() {19 API = gojsonApi{}20}2122type gojsonApi struct{}2324func (j gojsonApi) Marshal(v any) ([]byte, error) {25 return json.Marshal(v)26}2728func (j gojsonApi) Unmarshal(data []byte, v any) error {29 return json.Unmarshal(data, v)30}3132func (j gojsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {33 return json.MarshalIndent(v, prefix, indent)34}3536func (j gojsonApi) NewEncoder(writer io.Writer) Encoder {37 return json.NewEncoder(writer)38}3940func (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.45//go:build !jsoniter && !go_json && !(sonic && (linux || windows || darwin))67package json89import (10 "encoding/json"11 "io"12)1314// Package indicates what library is being used for JSON encoding.15const Package = "encoding/json"1617func init() {18 API = jsonApi{}19}2021type jsonApi struct{}2223func (j jsonApi) Marshal(v any) ([]byte, error) {24 return json.Marshal(v)25}2627func (j jsonApi) Unmarshal(data []byte, v any) error {28 return json.Unmarshal(data, v)29}3031func (j jsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {32 return json.MarshalIndent(v, prefix, indent)33}3435func (j jsonApi) NewEncoder(writer io.Writer) Encoder {36 return json.NewEncoder(writer)37}3839func (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.45//go:build jsoniter67package json89import (10 "io"1112 jsoniter "github.com/json-iterator/go"13)1415// Package indicates what library is being used for JSON encoding.16const Package = "github.com/json-iterator/go"1718func init() {19 API = jsoniterApi{}20}2122var json = jsoniter.ConfigCompatibleWithStandardLibrary2324type jsoniterApi struct{}2526func (j jsoniterApi) Marshal(v any) ([]byte, error) {27 return json.Marshal(v)28}2930func (j jsoniterApi) Unmarshal(data []byte, v any) error {31 return json.Unmarshal(data, v)32}3334func (j jsoniterApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {35 return json.MarshalIndent(v, prefix, indent)36}3738func (j jsoniterApi) NewEncoder(writer io.Writer) Encoder {39 return json.NewEncoder(writer)40}4142func (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.45//go:build sonic && (linux || windows || darwin)67package json89import (10 "io"1112 "github.com/bytedance/sonic"13)1415// Package indicates what library is being used for JSON encoding.16const Package = "github.com/bytedance/sonic"1718func init() {19 API = sonicApi{}20}2122var json = sonic.ConfigStd2324type sonicApi struct{}2526func (j sonicApi) Marshal(v any) ([]byte, error) {27 return json.Marshal(v)28}2930func (j sonicApi) Unmarshal(data []byte, v any) error {31 return json.Unmarshal(data, v)32}3334func (j sonicApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {35 return json.MarshalIndent(v, prefix, indent)36}3738func (j sonicApi) NewEncoder(writer io.Writer) Encoder {39 return json.NewEncoder(writer)40}4142func (j sonicApi) NewDecoder(reader io.Reader) Decoder {43 return json.NewDecoder(reader)44}
modified:docs/doc.md+60 added
61 unmodified lines
62 - [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)6970## Build tags
2300 unmodified lines
2371 router.Run()2372}2373```23742375### Custom json codec at runtime23762377Gin support custom json serialization and deserialization logic without using compile tags.237823791. Define a custom struct implements the `json.Core` interface.238023812. Before your engine starts, assign values to `json.API` using the custom struct.23822383```go2384package main23852386import (2387 "io"23882389 "github.com/gin-gonic/gin"2390 "github.com/gin-gonic/gin/codec/json"2391 jsoniter "github.com/json-iterator/go"2392)23932394var customConfig = jsoniter.Config{2395 EscapeHTML: true,2396 SortMapKeys: true,2397 ValidateJsonRawMessage: true,2398}.Froze()23992400// implement api.JsonApi2401type customJsonApi struct {2402}24032404func (j customJsonApi) Marshal(v any) ([]byte, error) {2405 return customConfig.Marshal(v)2406}24072408func (j customJsonApi) Unmarshal(data []byte, v any) error {2409 return customConfig.Unmarshal(data, v)2410}24112412func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {2413 return customConfig.MarshalIndent(v, prefix, indent)2414}24152416func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {2417 return customConfig.NewEncoder(writer)2418}24192420func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {2421 return customConfig.NewDecoder(reader)2422}24232424func main() {2425 //Replace the default json api2426 json.API = customJsonApi{}24272428 //Start your gin engine2429 router := gin.Default()2430 router.Run(":8080")2431}2432```24332434## Don't trust all proxies24352436Gin lets you specify which headers to hold the real client IP (if any),2437as well as specifying which proxies (or direct clients) you trust to
120 unmodified lines
deleted: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.45//go:build go_json67package json89import json "github.com/goccy/go-json"1011var (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)2324// Package indicates what library is being used for JSON encoding.25const 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.45//go:build !jsoniter && !go_json && !(sonic && (linux || windows || darwin))67package json89import "encoding/json"1011var (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)2324// Package indicates what library is being used for JSON encoding.25const 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.45//go:build jsoniter67package json89import jsoniter "github.com/json-iterator/go"1011var (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)2425// Package indicates what library is being used for JSON encoding.26const 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.45//go:build sonic && (linux || windows || darwin)67package json89import "github.com/bytedance/sonic"1011var (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)2425// Package indicates what library is being used for JSON encoding.26const Package = "github.com/bytedance/sonic"
modified:render/json.go+7 added-7 removed
9 unmodified lines
10 "html/template"11 "net/http"12 "unicode"1314 "github.com/gin-gonic/gin/codec/json"15 "github.com/gin-gonic/gin/internal/bytesconv"15 "github.com/gin-gonic/gin/internal/json"16)1718// JSON contains the given interface object.19type JSON struct {
45 unmodified lines
6566// WriteJSON marshals the given interface object and writes it with custom ContentType.67func 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 lines
7677// Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType.78func (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 lines
9293// Render (SecureJSON) marshals the given interface object and writes it with custom ContentType.94func (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 values
14 unmodified lines
115116// Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType.117func (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 lines
153154// Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType.155func (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 lines
182183// Render (PureJSON) writes custom ContentType and encodes the given interface object.184func (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 lines
modified:render/render_test.go+2 added-2 removed
13 unmodified lines
14 "strconv"15 "strings"16 "testing"1718 "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 lines
172 ew.bufString = `(`173 err = jsonpJSON.Render(ew)174 assert.Equal(t, `write "`+`(`+`" error`, err.Error())175176 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 lines
modified:context_test.go+1 added-1 removed
26 unmodified lines
27 "time"2829 "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 lines
modified:errors_test.go+4 added-4 removed
7 unmodified lines
8 "errors"9 "fmt"10 "testing"1112 "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 lines
32 "error": baseError.Error(),33 "meta": "some data",34 }, err.JSON())3536 jsonBytes, _ := json.Marshal(err)36 jsonBytes, _ := json.API.Marshal(err)37 assert.JSONEq(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))3839 err.SetMeta(H{ //nolint: errcheck40 "status": "200",
50 unmodified lines
91 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))103104 errs = errorMsgs{}105 assert.Nil(t, errs.Last())
35 unmodified lines
modified:errors.go+3 added-3 removed
7 unmodified lines
8 "fmt"9 "reflect"10 "strings"1112 "github.com/gin-gonic/gin/internal/json"12 "github.com/gin-gonic/gin/codec/json"13)1415// ErrorType is an unsigned 64-bit error code as defined in the gin spec.16type ErrorType uint64
59 unmodified lines
76}7778// MarshalJSON implements the json.Marshaller interface.79func (msg *Error) MarshalJSON() ([]byte, error) {80 return json.Marshal(msg.JSON())80 return json.API.Marshal(msg.JSON())81}8283// Error implements the error interface.84func (msg Error) Error() string {
71 unmodified lines
156}157158// MarshalJSON implements the json.Marshaller interface.159func (a errorMsgs) MarshalJSON() ([]byte, error) {160 return json.Marshal(a.JSON())160 return json.API.Marshal(a.JSON())161}162163func (a errorMsgs) String() string {164 if len(a) == 0 {
11 unmodified lines
modified:go.mod+1 added-1 removed
7 unmodified lines
8 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.12
13 unmodified lines
30 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 // indirect
9 unmodified lines