Skip to content

Commit

Permalink
Bug fix:
Browse files Browse the repository at this point in the history
 - fatal error: concurrent map writes(gin-contrib#15)
  • Loading branch information
zhangyi committed Aug 29, 2024
1 parent c7b2e17 commit d9d3b75
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
8 changes: 5 additions & 3 deletions timeout.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,11 @@ func New(opts ...Option) gin.HandlerFunc {
tw.FreeBuffer()
bufPool.Put(buffer)

c.Writer = w
t.response(c)
c.Writer = tw
// Copy gin.Context here to avoid concurrent writes to c.ResponseWriter's header(which is a map),
// see https://github.com/gin-contrib/timeout/issues/15
ctxCopy := c.Copy()
ctxCopy.Writer = w
t.response(ctxCopy)
}
}
}
23 changes: 23 additions & 0 deletions timeout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,26 @@ func TestPanic(t *testing.T) {
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Equal(t, "", w.Body.String())
}

func TestConcurrentHeaderWrites(t *testing.T) {
r := gin.New()
r.Use(gin.Recovery())
r.Use(New(
WithTimeout(time.Millisecond*50),
WithHandler(func(c *gin.Context) {
c.Next()
}),
))
r.GET("/", func(c *gin.Context) {
for {
c.Header("X-Foo", "bar")
}
})

w := httptest.NewRecorder()
req, err := http.NewRequest(http.MethodGet, "/", nil)

Check failure on line 120 in timeout_test.go

View workflow job for this annotation

GitHub Actions / lint

should rewrite http.NewRequestWithContext or add (*Request).WithContext (noctx)
if err != nil {
t.Fatal("http NewRequest: ", err)
}
r.ServeHTTP(w, req)
}

0 comments on commit d9d3b75

Please sign in to comment.