Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4df51ad

Browse files
Merge pull request gin-gonic#587 from roylou/develop
Write header immediately in AbortWithStatus(), close gin-gonic#585
2 parents 007bd51 + 4c4444b commit 4df51ad

File tree

5 files changed

+6
-10
lines changed

5 files changed

+6
-10
lines changed

context.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ func (c *Context) Abort() {
115115
// For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).
116116
func (c *Context) AbortWithStatus(code int) {
117117
c.Status(code)
118+
c.Writer.WriteHeaderNow()
118119
c.Abort()
119120
}
120121

context_test.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,6 @@ func TestContextAbortWithStatus(t *testing.T) {
556556
c, w, _ := CreateTestContext()
557557
c.index = 4
558558
c.AbortWithStatus(401)
559-
c.Writer.WriteHeaderNow()
560559

561560
assert.Equal(t, c.index, abortIndex)
562561
assert.Equal(t, c.Writer.Status(), 401)
@@ -607,7 +606,6 @@ func TestContextTypedError(t *testing.T) {
607606
func TestContextAbortWithError(t *testing.T) {
608607
c, w, _ := CreateTestContext()
609608
c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
610-
c.Writer.WriteHeaderNow()
611609

612610
assert.Equal(t, w.Code, 401)
613611
assert.Equal(t, c.index, abortIndex)

logger.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,9 @@ func ErrorLogger() HandlerFunc {
2828
func ErrorLoggerT(typ ErrorType) HandlerFunc {
2929
return func(c *Context) {
3030
c.Next()
31-
// avoid writting if we already wrote into the response body
32-
if !c.Writer.Written() {
33-
errors := c.Errors.ByType(typ)
34-
if len(errors) > 0 {
35-
c.JSON(-1, errors)
36-
}
31+
errors := c.Errors.ByType(typ)
32+
if len(errors) > 0 {
33+
c.JSON(-1, errors)
3734
}
3835
}
3936
}

logger_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ func TestErrorLogger(t *testing.T) {
116116

117117
w = performRequest(router, "GET", "/print")
118118
assert.Equal(t, w.Code, 500)
119-
assert.Equal(t, w.Body.String(), "hola!")
119+
assert.Equal(t, w.Body.String(), "hola!{\"error\":\"this is an error\"}\n")
120120
}
121121

122122
func TestSkippingPaths(t *testing.T) {

recovery_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,5 @@ func TestPanicWithAbort(t *testing.T) {
3939
// RUN
4040
w := performRequest(router, "GET", "/recovery")
4141
// TEST
42-
assert.Equal(t, w.Code, 500) // NOT SURE
42+
assert.Equal(t, w.Code, 400)
4343
}

0 commit comments

Comments
 (0)