Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix rewrite status code warning #51

Closed

Conversation

sasakiyori
Copy link

@sasakiyori sasakiyori commented Jul 12, 2023

gin warning:

[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with 401

reproduced by following code:

func main() {
	g := gin.New()
	g.Use(TimeoutMiddleware(), AbortHandler())
	g.GET("/test", func(c *gin.Context) {
		time.Sleep(time.Second * 1000)
		c.Data(200, "text/plain", []byte("test"))
	})

	server := &http.Server{
		Addr:         ":6666",
		Handler:      g,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 0,
		IdleTimeout:  10 * time.Second,
	}

	_ = server.ListenAndServe()
}

func TimeoutMiddleware() gin.HandlerFunc {
	return timeout.New(
		timeout.WithTimeout(1500*time.Second),
		timeout.WithHandler(func(c *gin.Context) {
			c.Next()
		}),
		timeout.WithResponse(func(c *gin.Context) {
			c.String(404, "timeout")
		}),
	)
}

func AbortHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.AbortWithStatus(401)
	}
}

The reason is AbortWithStatus will firstly call WriteHeader and then call WriteHeaderNow for double check (confirm the header already be written and the http status code is not modified).

In the master branch, WriteHeader implemented by timeout repo, but WriteHeaderNow implemented by gin repo. And this cause the double write for http status code and the failure.

@appleboy appleboy closed this in #63 Nov 25, 2023
appleboy added a commit that referenced this pull request Nov 25, 2023
- Add a `Status` method to the `Writer` struct
- Modify the `TestWriter_Status` test function to include the new `Status` method

fixed by @zhyee

fixed #52
fixed #51

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant