mirror of
https://github.com/gin-gonic/gin.git
synced 2025-08-07 11:49:48 +08:00
feat: added AbortWithStatusPureJSON()
in Context
(#4290)
* feat: added `AbortWithStatusPureJSON()` in context * Update context_test.go
This commit is contained in:
parent
b7d6308bcc
commit
dbd8a25150
@ -216,6 +216,14 @@ func (c *Context) AbortWithStatus(code int) {
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
// AbortWithStatusJSON calls `Abort()` and then `PureJSON` internally.
|
||||
// This method stops the chain, writes the status code and return a JSON body without escaping.
|
||||
// It also sets the Content-Type as "application/json".
|
||||
func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any) {
|
||||
c.Abort()
|
||||
c.PureJSON(code, jsonObj)
|
||||
}
|
||||
|
||||
// AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
|
||||
// This method stops the chain, writes the status code and return a JSON body.
|
||||
// It also sets the Content-Type as "application/json".
|
||||
|
@ -1680,6 +1680,32 @@ func TestContextAbortWithStatusJSON(t *testing.T) {
|
||||
assert.JSONEq(t, "{\"foo\":\"fooValue\",\"bar\":\"barValue\"}", jsonStringBody)
|
||||
}
|
||||
|
||||
func TestContextAbortWithStatusPureJSON(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.index = 4
|
||||
|
||||
in := new(testJSONAbortMsg)
|
||||
in.Bar = "barValue"
|
||||
in.Foo = "fooValue"
|
||||
|
||||
c.AbortWithStatusPureJSON(http.StatusUnsupportedMediaType, in)
|
||||
|
||||
assert.Equal(t, abortIndex, c.index)
|
||||
assert.Equal(t, http.StatusUnsupportedMediaType, c.Writer.Status())
|
||||
assert.Equal(t, http.StatusUnsupportedMediaType, w.Code)
|
||||
assert.True(t, c.IsAborted())
|
||||
|
||||
contentType := w.Header().Get("Content-Type")
|
||||
assert.Equal(t, "application/json; charset=utf-8", contentType)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
_, err := buf.ReadFrom(w.Body)
|
||||
require.NoError(t, err)
|
||||
jsonStringBody := buf.String()
|
||||
assert.JSONEq(t, "{\"foo\":\"fooValue\",\"bar\":\"barValue\"}", jsonStringBody)
|
||||
}
|
||||
|
||||
func TestContextError(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
assert.Empty(t, c.Errors)
|
||||
|
Loading…
x
Reference in New Issue
Block a user