mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-14 12:12:12 +08:00
Testing custom JSON render
This commit is contained in:
parent
ea103661a9
commit
6144ce5af3
@ -9,6 +9,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/gin-gonic/gin/render"
|
||||||
"html/template"
|
"html/template"
|
||||||
"io"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
@ -3123,3 +3124,32 @@ func TestContextNext(t *testing.T) {
|
|||||||
assert.True(t, exists)
|
assert.True(t, exists)
|
||||||
assert.Equal(t, "value3", value)
|
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": "<b>"})
|
||||||
|
|
||||||
|
t.Log(w.Body.String())
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user