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

Gzip middleware breaks Recovery middleware setting the status code #28

Open
segevfiner opened this issue Jul 9, 2019 · 3 comments
Open

Comments

@segevfiner
Copy link
Contributor

Build:

package main

import (
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.GET("/", func(c *gin.Context) {
		panic("panic")
	})
	r.Run()
}

Run:

$ curl -v --compressed http://localhost:8080/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Accept-Encoding: deflate, gzip
> 
< HTTP/1.1 200 OK
< Content-Encoding: gzip
< Vary: Accept-Encoding
< Date: Tue, 09 Jul 2019 10:02:44 GMT
< Content-Length: 23
< Content-Type: application/x-gzip
< 
* Connection #0 to host localhost left intact

You get the following warning from Gin:

[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with 500
@segevfiner
Copy link
Contributor Author

I think the cause is:

gzip/gzip.go

Lines 44 to 47 in aef065f

defer func() {
gz.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
}()
which happens before the Recovery middleware handles the panic and sets the status code, but I'm unsure on how to fix this.

@hmldd
Copy link

hmldd commented Mar 10, 2020

@segevfiner Try to move r.Use(gin.Recovery()) next to r.Use(gzip.Gzip(gzip.DefaultCompression)).

package main

import (
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.New()
	r.Use(gzip.Gzip(gzip.DefaultCompression))
	r.Use(gin.Recovery())
	r.Use(gin.Logger())

	r.GET("/", func(c *gin.Context) {
		panic("panic")
	})
	r.Run()
}

@pdeva
Copy link

pdeva commented Dec 29, 2021

i ran into this too. a config setting or some official documentation around this would be very helpful

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

No branches or pull requests

3 participants