feat: support custom json codec at runtime (#3391)

* 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
This commit is contained in:
Tim
2025-06-16 23:16:36 +08:00
committed by GitHub
parent 0a864884de
commit 688a429d19
19 changed files with 497 additions and 125 deletions
+4 -4
View File
@@ -9,7 +9,7 @@ import (
"fmt"
"testing"
"github.com/gin-gonic/gin/internal/json"
"github.com/gin-gonic/gin/codec/json"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -33,7 +33,7 @@ func TestError(t *testing.T) {
"meta": "some data",
}, err.JSON())
jsonBytes, _ := json.Marshal(err)
jsonBytes, _ := json.API.Marshal(err)
assert.JSONEq(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))
err.SetMeta(H{ //nolint: errcheck
@@ -92,13 +92,13 @@ Error #03: third
H{"error": "second", "meta": "some data"},
H{"error": "third", "status": "400"},
}, errs.JSON())
jsonBytes, _ := json.Marshal(errs)
jsonBytes, _ := json.API.Marshal(errs)
assert.JSONEq(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes))
errs = errorMsgs{
{Err: errors.New("first"), Type: ErrorTypePrivate},
}
assert.Equal(t, H{"error": "first"}, errs.JSON())
jsonBytes, _ = json.Marshal(errs)
jsonBytes, _ = json.API.Marshal(errs)
assert.JSONEq(t, "{\"error\":\"first\"}", string(jsonBytes))
errs = errorMsgs{}