pax_global_header00006660000000000000000000000064141555010210014504gustar00rootroot0000000000000052 comment=3d908a0e27701489e9603f415a7bb21c72c24a36 gzip-0.0.5/000077500000000000000000000000001415550102100124575ustar00rootroot00000000000000gzip-0.0.5/.github/000077500000000000000000000000001415550102100140175ustar00rootroot00000000000000gzip-0.0.5/.github/workflows/000077500000000000000000000000001415550102100160545ustar00rootroot00000000000000gzip-0.0.5/.github/workflows/go.yml000066400000000000000000000031741415550102100172110ustar00rootroot00000000000000name: Run Tests on: push: branches: - master pull_request: branches: - master jobs: lint: runs-on: ubuntu-latest steps: - name: Setup go uses: actions/setup-go@v2 with: go-version: '^1.16' - name: Checkout repository uses: actions/checkout@v2 - name: Setup golangci-lint uses: golangci/golangci-lint-action@v2 with: version: v1.42.1 args: --verbose test: strategy: matrix: os: [ubuntu-latest, macos-latest] go: [1.13, 1.14, 1.15, 1.16, 1.17] include: - os: ubuntu-latest go-build: ~/.cache/go-build - os: macos-latest go-build: ~/Library/Caches/go-build name: ${{ matrix.os }} @ Go ${{ matrix.go }} runs-on: ${{ matrix.os }} env: GO111MODULE: on GOPROXY: https://proxy.golang.org steps: - name: Set up Go ${{ matrix.go }} uses: actions/setup-go@v2 with: go-version: ${{ matrix.go }} - name: Checkout Code uses: actions/checkout@v2 with: ref: ${{ github.ref }} - uses: actions/cache@v2 with: path: | ${{ matrix.go-build }} ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ runner.os }}-go- - name: Run Tests run: | go test -v -covermode=atomic -coverprofile=coverage.out - name: Upload coverage to Codecov uses: codecov/codecov-action@v2 with: flags: ${{ matrix.os }},go-${{ matrix.go }} gzip-0.0.5/LICENSE000066400000000000000000000020521415550102100134630ustar00rootroot00000000000000MIT License Copyright (c) 2017 Gin-Gonic Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gzip-0.0.5/README.md000066400000000000000000000054221415550102100137410ustar00rootroot00000000000000# GZIP gin's middleware [![Run Tests](https://github.com/gin-contrib/gzip/actions/workflows/go.yml/badge.svg)](https://github.com/gin-contrib/gzip/actions/workflows/go.yml) [![codecov](https://codecov.io/gh/gin-contrib/gzip/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-contrib/gzip) [![Go Report Card](https://goreportcard.com/badge/github.com/gin-contrib/gzip)](https://goreportcard.com/report/github.com/gin-contrib/gzip) [![GoDoc](https://godoc.org/github.com/gin-contrib/gzip?status.svg)](https://godoc.org/github.com/gin-contrib/gzip) [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin) Gin middleware to enable `GZIP` support. ## Usage Download and install it: ```sh go get github.com/gin-contrib/gzip ``` Import it in your code: ```go import "github.com/gin-contrib/gzip" ``` Canonical example: ```go package main import ( "fmt" "net/http" "time" "github.com/gin-contrib/gzip" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.Use(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(":8080"); err != nil { log.Fatal(err) } } ``` Customized Excluded Extensions ```go package main import ( "fmt" "net/http" "time" "github.com/gin-contrib/gzip" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{".pdf", ".mp4"}))) 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(":8080"); err != nil { log.Fatal(err) } } ``` Customized Excluded Paths ```go package main import ( "fmt" "net/http" "time" "github.com/gin-contrib/gzip" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{"/api/"}))) 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(":8080"); err != nil { log.Fatal(err) } } ``` Customized Excluded Paths ```go package main import ( "fmt" "net/http" "time" "github.com/gin-contrib/gzip" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPathsRegexs([]string{".*"}))) 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(":8080"); err != nil { log.Fatal(err) } } ``` gzip-0.0.5/example/000077500000000000000000000000001415550102100141125ustar00rootroot00000000000000gzip-0.0.5/example/example.go000066400000000000000000000006261415550102100161000ustar00rootroot00000000000000package main import ( "fmt" "log" "net/http" "time" "github.com/gin-contrib/gzip" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.Use(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(":8080"); err != nil { log.Fatal(err) } } gzip-0.0.5/go.mod000066400000000000000000000001761415550102100135710ustar00rootroot00000000000000module github.com/gin-contrib/gzip require ( github.com/gin-gonic/gin v1.7.4 github.com/stretchr/testify v1.7.0 ) go 1.13 gzip-0.0.5/go.sum000066400000000000000000000123261415550102100136160ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.4 h1:QmUZXrvJ9qZ3GfWvQ+2wnW/1ePrTEJqPKMYEU3lD/DM= github.com/gin-gonic/gin v1.7.4/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gzip-0.0.5/gzip.go000066400000000000000000000015151415550102100137610ustar00rootroot00000000000000package gzip import ( "compress/gzip" "github.com/gin-gonic/gin" ) const ( BestCompression = gzip.BestCompression BestSpeed = gzip.BestSpeed DefaultCompression = gzip.DefaultCompression NoCompression = gzip.NoCompression ) func Gzip(level int, options ...Option) gin.HandlerFunc { return newGzipHandler(level, options...).Handle } type gzipWriter struct { gin.ResponseWriter writer *gzip.Writer } func (g *gzipWriter) WriteString(s string) (int, error) { g.Header().Del("Content-Length") return g.writer.Write([]byte(s)) } func (g *gzipWriter) Write(data []byte) (int, error) { g.Header().Del("Content-Length") return g.writer.Write(data) } // Fix: https://github.com/mholt/caddy/issues/38 func (g *gzipWriter) WriteHeader(code int) { g.Header().Del("Content-Length") g.ResponseWriter.WriteHeader(code) } gzip-0.0.5/gzip_test.go000066400000000000000000000155501415550102100150240ustar00rootroot00000000000000package gzip import ( "bytes" "compress/gzip" "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "strconv" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" ) const ( testResponse = "Gzip Test Response " testReverseResponse = "Gzip Test Reverse Response " ) func init() { gin.SetMode(gin.ReleaseMode) } type rServer struct{} func (s *rServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { fmt.Fprint(rw, testReverseResponse) } type closeNotifyingRecorder struct { *httptest.ResponseRecorder closed chan bool } func newCloseNotifyingRecorder() *closeNotifyingRecorder { return &closeNotifyingRecorder{ httptest.NewRecorder(), make(chan bool, 1), } } func (c *closeNotifyingRecorder) CloseNotify() <-chan bool { return c.closed } func newServer() *gin.Engine { // init reverse proxy server rServer := httptest.NewServer(new(rServer)) target, _ := url.Parse(rServer.URL) rp := httputil.NewSingleHostReverseProxy(target) router := gin.New() router.Use(Gzip(DefaultCompression)) router.GET("/", func(c *gin.Context) { c.Header("Content-Length", strconv.Itoa(len(testResponse))) c.String(200, testResponse) }) router.Any("/reverse", func(c *gin.Context) { rp.ServeHTTP(c.Writer, c.Request) }) return router } func TestGzip(t *testing.T) { req, _ := http.NewRequest("GET", "/", nil) req.Header.Add("Accept-Encoding", "gzip") w := httptest.NewRecorder() r := newServer() r.ServeHTTP(w, req) assert.Equal(t, w.Code, 200) assert.Equal(t, w.Header().Get("Content-Encoding"), "gzip") assert.Equal(t, w.Header().Get("Vary"), "Accept-Encoding") assert.NotEqual(t, w.Header().Get("Content-Length"), "0") assert.NotEqual(t, w.Body.Len(), 19) assert.Equal(t, fmt.Sprint(w.Body.Len()), w.Header().Get("Content-Length")) gr, err := gzip.NewReader(w.Body) assert.NoError(t, err) defer gr.Close() body, _ := ioutil.ReadAll(gr) assert.Equal(t, string(body), testResponse) } func TestGzipPNG(t *testing.T) { req, _ := http.NewRequest("GET", "/image.png", nil) req.Header.Add("Accept-Encoding", "gzip") router := gin.New() router.Use(Gzip(DefaultCompression)) router.GET("/image.png", func(c *gin.Context) { c.String(200, "this is a PNG!") }) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, w.Code, 200) assert.Equal(t, w.Header().Get("Content-Encoding"), "") assert.Equal(t, w.Header().Get("Vary"), "") assert.Equal(t, w.Body.String(), "this is a PNG!") } func TestExcludedExtensions(t *testing.T) { req, _ := http.NewRequest("GET", "/index.html", nil) req.Header.Add("Accept-Encoding", "gzip") router := gin.New() router.Use(Gzip(DefaultCompression, WithExcludedExtensions([]string{".html"}))) router.GET("/index.html", func(c *gin.Context) { c.String(200, "this is a HTML!") }) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "", w.Header().Get("Content-Encoding")) assert.Equal(t, "", w.Header().Get("Vary")) assert.Equal(t, "this is a HTML!", w.Body.String()) assert.Equal(t, "", w.Header().Get("Content-Length")) } func TestExcludedPaths(t *testing.T) { req, _ := http.NewRequest("GET", "/api/books", nil) req.Header.Add("Accept-Encoding", "gzip") router := gin.New() router.Use(Gzip(DefaultCompression, WithExcludedPaths([]string{"/api/"}))) router.GET("/api/books", func(c *gin.Context) { c.String(200, "this is books!") }) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "", w.Header().Get("Content-Encoding")) assert.Equal(t, "", w.Header().Get("Vary")) assert.Equal(t, "this is books!", w.Body.String()) assert.Equal(t, "", w.Header().Get("Content-Length")) } func TestNoGzip(t *testing.T) { req, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() r := newServer() r.ServeHTTP(w, req) assert.Equal(t, w.Code, 200) assert.Equal(t, w.Header().Get("Content-Encoding"), "") assert.Equal(t, w.Header().Get("Content-Length"), "19") assert.Equal(t, w.Body.String(), testResponse) } func TestGzipWithReverseProxy(t *testing.T) { req, _ := http.NewRequest("GET", "/reverse", nil) req.Header.Add("Accept-Encoding", "gzip") w := newCloseNotifyingRecorder() r := newServer() r.ServeHTTP(w, req) assert.Equal(t, w.Code, 200) assert.Equal(t, w.Header().Get("Content-Encoding"), "gzip") assert.Equal(t, w.Header().Get("Vary"), "Accept-Encoding") assert.NotEqual(t, w.Header().Get("Content-Length"), "0") assert.NotEqual(t, w.Body.Len(), 19) assert.Equal(t, fmt.Sprint(w.Body.Len()), w.Header().Get("Content-Length")) gr, err := gzip.NewReader(w.Body) assert.NoError(t, err) defer gr.Close() body, _ := ioutil.ReadAll(gr) assert.Equal(t, string(body), testReverseResponse) } func TestDecompressGzip(t *testing.T) { buf := &bytes.Buffer{} gz, _ := gzip.NewWriterLevel(buf, gzip.DefaultCompression) if _, err := gz.Write([]byte(testResponse)); err != nil { gz.Close() t.Fatal(err) } gz.Close() req, _ := http.NewRequest("POST", "/", buf) req.Header.Add("Content-Encoding", "gzip") router := gin.New() router.Use(Gzip(DefaultCompression, WithDecompressFn(DefaultDecompressHandle))) router.POST("/", func(c *gin.Context) { if v := c.Request.Header.Get("Content-Encoding"); v != "" { t.Errorf("unexpected `Content-Encoding`: %s header", v) } if v := c.Request.Header.Get("Content-Length"); v != "" { t.Errorf("unexpected `Content-Length`: %s header", v) } data, err := c.GetRawData() if err != nil { t.Fatal(err) } c.Data(200, "text/plain", data) }) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "", w.Header().Get("Content-Encoding")) assert.Equal(t, "", w.Header().Get("Vary")) assert.Equal(t, testResponse, w.Body.String()) assert.Equal(t, "", w.Header().Get("Content-Length")) } func TestDecompressGzipWithEmptyBody(t *testing.T) { req, _ := http.NewRequest("POST", "/", nil) req.Header.Add("Content-Encoding", "gzip") router := gin.New() router.Use(Gzip(DefaultCompression, WithDecompressFn(DefaultDecompressHandle))) router.POST("/", func(c *gin.Context) { c.String(200, "ok") }) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "", w.Header().Get("Content-Encoding")) assert.Equal(t, "", w.Header().Get("Vary")) assert.Equal(t, "ok", w.Body.String()) assert.Equal(t, "", w.Header().Get("Content-Length")) } func TestDecompressGzipWithIncorrectData(t *testing.T) { req, _ := http.NewRequest("POST", "/", bytes.NewReader([]byte(testResponse))) req.Header.Add("Content-Encoding", "gzip") router := gin.New() router.Use(Gzip(DefaultCompression, WithDecompressFn(DefaultDecompressHandle))) router.POST("/", func(c *gin.Context) { c.String(200, "ok") }) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) } gzip-0.0.5/handler.go000066400000000000000000000031541415550102100144260ustar00rootroot00000000000000package gzip import ( "compress/gzip" "fmt" "io/ioutil" "net/http" "path/filepath" "strings" "sync" "github.com/gin-gonic/gin" ) type gzipHandler struct { *Options gzPool sync.Pool } func newGzipHandler(level int, options ...Option) *gzipHandler { handler := &gzipHandler{ Options: DefaultOptions, gzPool: sync.Pool{ New: func() interface{} { gz, err := gzip.NewWriterLevel(ioutil.Discard, level) if err != nil { panic(err) } return gz }, }, } for _, setter := range options { setter(handler.Options) } return handler } func (g *gzipHandler) Handle(c *gin.Context) { if fn := g.DecompressFn; fn != nil && c.Request.Header.Get("Content-Encoding") == "gzip" { fn(c) } if !g.shouldCompress(c.Request) { return } gz := g.gzPool.Get().(*gzip.Writer) defer g.gzPool.Put(gz) defer gz.Reset(ioutil.Discard) gz.Reset(c.Writer) c.Header("Content-Encoding", "gzip") c.Header("Vary", "Accept-Encoding") c.Writer = &gzipWriter{c.Writer, gz} defer func() { gz.Close() c.Header("Content-Length", fmt.Sprint(c.Writer.Size())) }() c.Next() } func (g *gzipHandler) shouldCompress(req *http.Request) bool { if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") || strings.Contains(req.Header.Get("Connection"), "Upgrade") || strings.Contains(req.Header.Get("Accept"), "text/event-stream") { return false } extension := filepath.Ext(req.URL.Path) if g.ExcludedExtensions.Contains(extension) { return false } if g.ExcludedPaths.Contains(req.URL.Path) { return false } if g.ExcludedPathesRegexs.Contains(req.URL.Path) { return false } return true } gzip-0.0.5/options.go000066400000000000000000000045351415550102100145100ustar00rootroot00000000000000package gzip import ( "compress/gzip" "net/http" "regexp" "strings" "github.com/gin-gonic/gin" ) var ( DefaultExcludedExtentions = NewExcludedExtensions([]string{ ".png", ".gif", ".jpeg", ".jpg", }) DefaultOptions = &Options{ ExcludedExtensions: DefaultExcludedExtentions, } ) type Options struct { ExcludedExtensions ExcludedExtensions ExcludedPaths ExcludedPaths ExcludedPathesRegexs ExcludedPathesRegexs DecompressFn func(c *gin.Context) } type Option func(*Options) func WithExcludedExtensions(args []string) Option { return func(o *Options) { o.ExcludedExtensions = NewExcludedExtensions(args) } } func WithExcludedPaths(args []string) Option { return func(o *Options) { o.ExcludedPaths = NewExcludedPaths(args) } } func WithExcludedPathsRegexs(args []string) Option { return func(o *Options) { o.ExcludedPathesRegexs = NewExcludedPathesRegexs(args) } } func WithDecompressFn(decompressFn func(c *gin.Context)) Option { return func(o *Options) { o.DecompressFn = decompressFn } } // Using map for better lookup performance type ExcludedExtensions map[string]bool func NewExcludedExtensions(extensions []string) ExcludedExtensions { res := make(ExcludedExtensions) for _, e := range extensions { res[e] = true } return res } func (e ExcludedExtensions) Contains(target string) bool { _, ok := e[target] return ok } type ExcludedPaths []string func NewExcludedPaths(paths []string) ExcludedPaths { return ExcludedPaths(paths) } func (e ExcludedPaths) Contains(requestURI string) bool { for _, path := range e { if strings.HasPrefix(requestURI, path) { return true } } return false } type ExcludedPathesRegexs []*regexp.Regexp func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs { result := make([]*regexp.Regexp, len(regexs)) for i, reg := range regexs { result[i] = regexp.MustCompile(reg) } return result } func (e ExcludedPathesRegexs) Contains(requestURI string) bool { for _, reg := range e { if reg.MatchString(requestURI) { return true } } return false } func DefaultDecompressHandle(c *gin.Context) { if c.Request.Body == nil { return } r, err := gzip.NewReader(c.Request.Body) if err != nil { _ = c.AbortWithError(http.StatusBadRequest, err) return } c.Request.Header.Del("Content-Encoding") c.Request.Header.Del("Content-Length") c.Request.Body = r }