Skip to content

Commit

Permalink
Merge pull request gin-gonic#587 from roylou/develop
Browse files Browse the repository at this point in the history
Write header immediately in AbortWithStatus(), close gin-gonic#585
  • Loading branch information
javierprovecho committed Apr 14, 2016
2 parents 007bd51 + 4c4444b commit 4df51ad
Show file tree
Hide file tree
Showing 5 changed files with 6 additions and 10 deletions.
1 change: 1 addition & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func (c *Context) Abort() {
// For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).
func (c *Context) AbortWithStatus(code int) {
c.Status(code)
c.Writer.WriteHeaderNow()
c.Abort()
}

Expand Down
2 changes: 0 additions & 2 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,6 @@ func TestContextAbortWithStatus(t *testing.T) {
c, w, _ := CreateTestContext()
c.index = 4
c.AbortWithStatus(401)
c.Writer.WriteHeaderNow()

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

assert.Equal(t, w.Code, 401)
assert.Equal(t, c.index, abortIndex)
Expand Down
9 changes: 3 additions & 6 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,9 @@ func ErrorLogger() HandlerFunc {
func ErrorLoggerT(typ ErrorType) HandlerFunc {
return func(c *Context) {
c.Next()
// avoid writting if we already wrote into the response body
if !c.Writer.Written() {
errors := c.Errors.ByType(typ)
if len(errors) > 0 {
c.JSON(-1, errors)
}
errors := c.Errors.ByType(typ)
if len(errors) > 0 {
c.JSON(-1, errors)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func TestErrorLogger(t *testing.T) {

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

func TestSkippingPaths(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ func TestPanicWithAbort(t *testing.T) {
// RUN
w := performRequest(router, "GET", "/recovery")
// TEST
assert.Equal(t, w.Code, 500) // NOT SURE
assert.Equal(t, w.Code, 400)
}

0 comments on commit 4df51ad

Please sign in to comment.