From 6144ce5af33a146aac32c3949ddde845e8136703 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=B1=E5=AE=97=E8=BE=89?= <1050527083@qq.com> Date: Sat, 16 Nov 2024 02:34:02 +0800 Subject: [PATCH] Testing custom JSON render --- context_test.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/context_test.go b/context_test.go index 5b63a647..7ddc4079 100644 --- a/context_test.go +++ b/context_test.go @@ -9,6 +9,7 @@ import ( "context" "errors" "fmt" + "github.com/gin-gonic/gin/render" "html/template" "io" "io/fs" @@ -3123,3 +3124,32 @@ func TestContextNext(t *testing.T) { assert.True(t, exists) assert.Equal(t, "value3", value) } + +// MyJSON customizing JSON rendering +type MyJSON struct { + Data any + render.JSON +} + +// Render rewrite the Render function +func (r MyJSON) Render(w http.ResponseWriter) error { + _, err := w.Write([]byte("test")) + return err +} + +func NewMyJSON(data any) render.Render { + return &MyJSON{Data: data} +} + +// TestCustomJSONRender the test uses a custom JSON render. +// The final result is that the user can customize the JSON render without affecting the original function. +func TestCustomJSONRender(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + c.RegisterJsonRender("MyTestJSON", NewMyJSON) + c.SetJSONRender("MyTestJSON") + + c.JSON(http.StatusCreated, H{"foo": "bar", "html": ""}) + + t.Log(w.Body.String()) +}