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

If enable the gzip middleware, the gin server returns an incorrect response for 404 status by default #46

Open
mstmdev opened this issue Dec 29, 2021 · 1 comment

Comments

@mstmdev
Copy link

mstmdev commented Dec 29, 2021

Enable the gzip middleware, that 404 response like this:

HTTP/1.1 404 Not Found
Vary: Accept-Encoding
Date: Wed, 29 Dec 2021 09:44:42 GMT
Content-Length: 0

Disable the gzip middleware, that 404 response like this:

HTTP/1.1 404 Not Found
Content-Type: text/plain
Date: Wed, 29 Dec 2021 09:47:08 GMT
Content-Length: 18

404 page not found

Because of the gz.Close() will writing the GZIP footer to c.Writer.

gzip/handler.go

Lines 55 to 60 in c784c8e

c.Writer = &gzipWriter{c.Writer, gz}
defer func() {
gz.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
}()
c.Next()

So gin will not write default404Body in serveError func.
We need to customize the gin.Engine.NoRoute that responds to the correct 404 content now.

https://github.com/gin-gonic/gin/blob/d062a6a6155236883f4c3292379ab94b1eac8b05/gin.go#L632-L637

@mstmdev mstmdev changed the title If enable the gzip middleware, the gin server response incorrect for 404 not found by default If enable the gzip middleware, the gin server returns an incorrect response for 404 status by default Dec 29, 2021
@runephilosof-karnovgroup

I see almost the same results.

runephilosof@fedora:~/code/go-test$ curl -i -H 'Accept-Encoding: gzip' localhost:9000/
HTTP/1.1 404 Not Found
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Wed, 20 Sep 2023 12:18:32 GMT
Content-Length: 23

But the 23 bytes is just the gzip overhead for an empty string

~/code/go-test$ curl -H 'Accept-Encoding: gzip' localhost:9000/ --output foo.gz
~/code/go-test$ gunzip foo.gz
~/code/go-test$ ls -l foo
-rw-r--r--. 1 runephilosof runephilosof 0 Sep 20 14:22 foo

Using

package main

import (
	"fmt"
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func main() {

	r := gin.Default()
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Add("Vary", "Origin")
	}, gzip.Gzip(gzip.DefaultCompression))
	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
	})

	// Listen and Server in 0.0.0.0:8080
	if err := r.Run(":9000"); err != nil {
		log.Fatal(err)
	}

}

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

2 participants