Skip to content

Commit dbd8a25

Browse files
authored
feat: added AbortWithStatusPureJSON() in Context (#4290)
* feat: added `AbortWithStatusPureJSON()` in context * Update context_test.go
1 parent b7d6308 commit dbd8a25

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

context.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,14 @@ func (c *Context) AbortWithStatus(code int) {
216216
c.Abort()
217217
}
218218

219+
// AbortWithStatusJSON calls `Abort()` and then `PureJSON` internally.
220+
// This method stops the chain, writes the status code and return a JSON body without escaping.
221+
// It also sets the Content-Type as "application/json".
222+
func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any) {
223+
c.Abort()
224+
c.PureJSON(code, jsonObj)
225+
}
226+
219227
// AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
220228
// This method stops the chain, writes the status code and return a JSON body.
221229
// It also sets the Content-Type as "application/json".

context_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,32 @@ func TestContextAbortWithStatusJSON(t *testing.T) {
16801680
assert.JSONEq(t, "{\"foo\":\"fooValue\",\"bar\":\"barValue\"}", jsonStringBody)
16811681
}
16821682

1683+
func TestContextAbortWithStatusPureJSON(t *testing.T) {
1684+
w := httptest.NewRecorder()
1685+
c, _ := CreateTestContext(w)
1686+
c.index = 4
1687+
1688+
in := new(testJSONAbortMsg)
1689+
in.Bar = "barValue"
1690+
in.Foo = "fooValue"
1691+
1692+
c.AbortWithStatusPureJSON(http.StatusUnsupportedMediaType, in)
1693+
1694+
assert.Equal(t, abortIndex, c.index)
1695+
assert.Equal(t, http.StatusUnsupportedMediaType, c.Writer.Status())
1696+
assert.Equal(t, http.StatusUnsupportedMediaType, w.Code)
1697+
assert.True(t, c.IsAborted())
1698+
1699+
contentType := w.Header().Get("Content-Type")
1700+
assert.Equal(t, "application/json; charset=utf-8", contentType)
1701+
1702+
buf := new(bytes.Buffer)
1703+
_, err := buf.ReadFrom(w.Body)
1704+
require.NoError(t, err)
1705+
jsonStringBody := buf.String()
1706+
assert.JSONEq(t, "{\"foo\":\"fooValue\",\"bar\":\"barValue\"}", jsonStringBody)
1707+
}
1708+
16831709
func TestContextError(t *testing.T) {
16841710
c, _ := CreateTestContext(httptest.NewRecorder())
16851711
assert.Empty(t, c.Errors)

0 commit comments

Comments
 (0)