mirror of
https://github.com/gin-gonic/gin.git
synced 2026-07-24 22:55:45 +08:00
Compare commits
9 Commits
8d5c5c7619
...
b69e11d1b3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b69e11d1b3 | ||
|
|
5260de6a83 | ||
|
|
5f424ff6f6 | ||
|
|
216a4a7c28 | ||
|
|
92006a5512 | ||
|
|
8ca6e308c6 | ||
|
|
7ae74c5272 | ||
|
|
9a76687101 | ||
|
|
e0109c70d9 |
@ -830,7 +830,11 @@ func TestUriBinding(t *testing.T) {
|
||||
}
|
||||
var not NotSupportStruct
|
||||
require.Error(t, b.BindUri(m, ¬))
|
||||
assert.Equal(t, map[string]any(nil), not.Name)
|
||||
require.Error(t, b.BindUri(m, ¬))
|
||||
// Check that if the map is not nil, it is empty (json-iterator may allocate map before error)
|
||||
if not.Name != nil {
|
||||
assert.Empty(t, not.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUriInnerBinding(t *testing.T) {
|
||||
|
||||
@ -2110,7 +2110,7 @@ func TestContextBindRequestTooLarge(t *testing.T) {
|
||||
// https://github.com/goccy/go-json/issues/485
|
||||
var expectedCode int
|
||||
switch json.Package {
|
||||
case "github.com/goccy/go-json":
|
||||
case "github.com/goccy/go-json", "github.com/json-iterator/go":
|
||||
expectedCode = http.StatusBadRequest
|
||||
default:
|
||||
expectedCode = http.StatusRequestEntityTooLarge
|
||||
|
||||
26
examples/json-iterator/README.md
Normal file
26
examples/json-iterator/README.md
Normal file
@ -0,0 +1,26 @@
|
||||
# JSON Iterator Example
|
||||
|
||||
This example demonstrates how to integrate [json-iterator/go](https://github.com/json-iterator/go) with Gin to replace the default encoding/json for better performance.
|
||||
|
||||
## How it works
|
||||
|
||||
Gin supports custom JSON serialization and deserialization logic via the `json.API` variable. By implementing the `json.Core` interface (which includes `Marshal`, `Unmarshal`, `NewEncoder`, `NewDecoder` etc.), we can swap out the underlying JSON engine.
|
||||
|
||||
## Usage
|
||||
|
||||
1. Define your custom configuration using `jsoniter.Config`.
|
||||
2. Implement the `json.Core` interface wrappers.
|
||||
3. Assign your custom implementation to `json.API` before creating the Gin engine.
|
||||
|
||||
## Run the example
|
||||
|
||||
```bash
|
||||
go run main.go
|
||||
```
|
||||
|
||||
Test it:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8080/ping
|
||||
# Output: {"message":"pong"}
|
||||
```
|
||||
45
examples/json-iterator/json_iterator_test.go
Normal file
45
examples/json-iterator/json_iterator_test.go
Normal file
@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
ginjson "github.com/gin-gonic/gin/codec/json"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestJsonIterator(t *testing.T) {
|
||||
// Restore default json api after test
|
||||
originalAPI := ginjson.API
|
||||
defer func() {
|
||||
ginjson.API = originalAPI
|
||||
}()
|
||||
|
||||
// Use custom json api
|
||||
ginjson.API = customJsonApi{}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.GET("/test", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"hello": "world",
|
||||
"foo": "bar",
|
||||
})
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/test", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
// Verify JSON response
|
||||
var response map[string]string
|
||||
err := json.Unmarshal(w.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "world", response["hello"])
|
||||
assert.Equal(t, "bar", response["foo"])
|
||||
}
|
||||
55
examples/json-iterator/main.go
Normal file
55
examples/json-iterator/main.go
Normal file
@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/codec/json"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
)
|
||||
|
||||
var customConfig = jsoniter.Config{
|
||||
EscapeHTML: true,
|
||||
SortMapKeys: true,
|
||||
ValidateJsonRawMessage: true,
|
||||
}.Froze()
|
||||
|
||||
// customJsonApi implement api.JsonApi
|
||||
type customJsonApi struct {
|
||||
}
|
||||
|
||||
func (j customJsonApi) Marshal(v any) ([]byte, error) {
|
||||
return customConfig.Marshal(v)
|
||||
}
|
||||
|
||||
func (j customJsonApi) Unmarshal(data []byte, v any) error {
|
||||
return customConfig.Unmarshal(data, v)
|
||||
}
|
||||
|
||||
func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {
|
||||
return customConfig.MarshalIndent(v, prefix, indent)
|
||||
}
|
||||
|
||||
func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {
|
||||
return customConfig.NewEncoder(writer)
|
||||
}
|
||||
|
||||
func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {
|
||||
return customConfig.NewDecoder(reader)
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Replace the default json api with json-iterator
|
||||
json.API = customJsonApi{}
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
r.GET("/ping", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "pong",
|
||||
})
|
||||
})
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
@ -64,7 +64,20 @@ func testRequest(t *testing.T, params ...string) {
|
||||
}
|
||||
|
||||
func TestRunEmpty(t *testing.T) {
|
||||
os.Setenv("PORT", "")
|
||||
// Listen on a random available port to avoid conflicts
|
||||
l, err := net.Listen("tcp", "localhost:0")
|
||||
require.NoError(t, err)
|
||||
defer l.Close()
|
||||
addr := l.Addr().String()
|
||||
_, port, err := net.SplitHostPort(addr)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Close the listener so router.Run() can bind to it (there's a small race here, but better than hardcoded 8080)
|
||||
// Actually, router.Run() calls http.ListenAndServe which creates its own listener.
|
||||
// If we close 'l', 'router.Run' can pick it up.
|
||||
l.Close()
|
||||
|
||||
os.Setenv("PORT", port)
|
||||
router := New()
|
||||
go func() {
|
||||
router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
|
||||
@ -72,11 +85,11 @@ func TestRunEmpty(t *testing.T) {
|
||||
}()
|
||||
|
||||
// Wait for server to be ready with exponential backoff
|
||||
err := waitForServerReady("http://localhost:8080/example", 10)
|
||||
err = waitForServerReady("http://"+addr+"/example", 10)
|
||||
require.NoError(t, err, "server should start successfully")
|
||||
|
||||
require.Error(t, router.Run(":8080"))
|
||||
testRequest(t, "http://localhost:8080/example")
|
||||
require.Error(t, router.Run(":"+port))
|
||||
testRequest(t, "http://"+addr+"/example")
|
||||
}
|
||||
|
||||
func TestBadTrustedCIDRs(t *testing.T) {
|
||||
|
||||
12
go.mod
12
go.mod
@ -5,7 +5,7 @@ go 1.24.0
|
||||
toolchain go1.24.7
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.14.2
|
||||
github.com/bytedance/sonic v1.15.0
|
||||
github.com/gin-contrib/sse v1.1.0
|
||||
github.com/go-playground/validator/v10 v10.28.0
|
||||
github.com/goccy/go-json v0.10.5
|
||||
@ -18,7 +18,7 @@ require (
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/ugorji/go/codec v1.3.1
|
||||
go.mongodb.org/mongo-driver v1.17.9
|
||||
golang.org/x/net v0.49.0
|
||||
golang.org/x/net v0.50.0
|
||||
google.golang.org/protobuf v1.36.10
|
||||
)
|
||||
|
||||
@ -26,7 +26,7 @@ require gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
require (
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic/loader v0.4.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 // indirect
|
||||
@ -41,7 +41,7 @@ require (
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
go.uber.org/mock v0.6.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/crypto v0.47.0 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
)
|
||||
|
||||
24
go.sum
24
go.sum
@ -1,9 +1,9 @@
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPIIE=
|
||||
github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980=
|
||||
github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o=
|
||||
github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
@ -77,15 +77,15 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
@ -16,9 +16,6 @@ import (
|
||||
"github.com/ugorji/go/codec"
|
||||
)
|
||||
|
||||
// TODO unit tests
|
||||
// test errors
|
||||
|
||||
func TestRenderMsgPack(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
data := map[string]any{
|
||||
@ -32,13 +29,52 @@ func TestRenderMsgPack(t *testing.T) {
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
h := new(codec.MsgpackHandle)
|
||||
assert.NotNil(t, h)
|
||||
buf := bytes.NewBuffer([]byte{})
|
||||
assert.NotNil(t, buf)
|
||||
err = codec.NewEncoder(buf, h).Encode(data)
|
||||
|
||||
var decoded map[string]any
|
||||
var mh codec.MsgpackHandle
|
||||
mh.RawToString = true
|
||||
err = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, w.Body.String(), buf.String())
|
||||
assert.Equal(t, data, decoded)
|
||||
assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestWriteMsgPack(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
data := map[string]any{
|
||||
"foo": "bar",
|
||||
"num": 42,
|
||||
}
|
||||
|
||||
err := WriteMsgPack(w, data)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
|
||||
var decoded map[string]any
|
||||
var mh codec.MsgpackHandle
|
||||
mh.RawToString = true
|
||||
err = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, decoded, 2)
|
||||
assert.Equal(t, "bar", decoded["foo"])
|
||||
assert.EqualValues(t, 42, decoded["num"])
|
||||
}
|
||||
|
||||
type failWriter struct {
|
||||
*httptest.ResponseRecorder
|
||||
}
|
||||
|
||||
func (w *failWriter) Write(data []byte) (int, error) {
|
||||
return 0, errors.New("write error")
|
||||
}
|
||||
|
||||
func TestRenderMsgPackError(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
data := map[string]any{
|
||||
"foo": "bar",
|
||||
}
|
||||
|
||||
err := (MsgPack{data}).Render(&failWriter{w})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "write error")
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user