summaryrefslogtreecommitdiff
path: root/vendor/github.com/gin-contrib/gzip
diff options
context:
space:
mode:
authorLibravatar Terin Stock <terinjokes@gmail.com>2025-03-09 17:47:56 +0100
committerLibravatar Terin Stock <terinjokes@gmail.com>2025-03-10 01:59:49 +0100
commit3ac1ee16f377d31a0fb80c8dae28b6239ac4229e (patch)
treef61faa581feaaeaba2542b9f2b8234a590684413 /vendor/github.com/gin-contrib/gzip
parent[chore] update URLs to forked source (diff)
downloadgotosocial-3ac1ee16f377d31a0fb80c8dae28b6239ac4229e.tar.xz
[chore] remove vendor
Diffstat (limited to 'vendor/github.com/gin-contrib/gzip')
-rw-r--r--vendor/github.com/gin-contrib/gzip/.gitignore1
-rw-r--r--vendor/github.com/gin-contrib/gzip/.golangci.yml38
-rw-r--r--vendor/github.com/gin-contrib/gzip/.goreleaser.yaml29
-rw-r--r--vendor/github.com/gin-contrib/gzip/LICENSE21
-rw-r--r--vendor/github.com/gin-contrib/gzip/README.md169
-rw-r--r--vendor/github.com/gin-contrib/gzip/gzip.go67
-rw-r--r--vendor/github.com/gin-contrib/gzip/handler.go117
-rw-r--r--vendor/github.com/gin-contrib/gzip/options.go270
8 files changed, 0 insertions, 712 deletions
diff --git a/vendor/github.com/gin-contrib/gzip/.gitignore b/vendor/github.com/gin-contrib/gzip/.gitignore
deleted file mode 100644
index 2d830686d..000000000
--- a/vendor/github.com/gin-contrib/gzip/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-coverage.out
diff --git a/vendor/github.com/gin-contrib/gzip/.golangci.yml b/vendor/github.com/gin-contrib/gzip/.golangci.yml
deleted file mode 100644
index d5cbd0a39..000000000
--- a/vendor/github.com/gin-contrib/gzip/.golangci.yml
+++ /dev/null
@@ -1,38 +0,0 @@
-linters:
- enable-all: false
- disable-all: true
- fast: false
- enable:
- - bodyclose
- - dogsled
- - dupl
- - errcheck
- - exportloopref
- - exhaustive
- - gochecknoinits
- - goconst
- - gocritic
- - gocyclo
- - gofmt
- - goimports
- - goprintffuncname
- - gosec
- - gosimple
- - govet
- - ineffassign
- - lll
- - misspell
- - nakedret
- - noctx
- - nolintlint
- - rowserrcheck
- - staticcheck
- - stylecheck
- - typecheck
- - unconvert
- - unparam
- - unused
- - whitespace
- - gofumpt
-run:
- timeout: 3m
diff --git a/vendor/github.com/gin-contrib/gzip/.goreleaser.yaml b/vendor/github.com/gin-contrib/gzip/.goreleaser.yaml
deleted file mode 100644
index 4c910add4..000000000
--- a/vendor/github.com/gin-contrib/gzip/.goreleaser.yaml
+++ /dev/null
@@ -1,29 +0,0 @@
-builds:
- - # If true, skip the build.
- # Useful for library projects.
- # Default is false
- skip: true
-
-changelog:
- use: github
- groups:
- - title: Features
- regexp: "^.*feat[(\\w)]*:+.*$"
- order: 0
- - title: "Bug fixes"
- regexp: "^.*fix[(\\w)]*:+.*$"
- order: 1
- - title: "Enhancements"
- regexp: "^.*chore[(\\w)]*:+.*$"
- order: 2
- - title: "Refactor"
- regexp: "^.*refactor[(\\w)]*:+.*$"
- order: 3
- - title: "Build process updates"
- regexp: ^.*?(build|ci)(\(.+\))??!?:.+$
- order: 4
- - title: "Documentation updates"
- regexp: ^.*?docs?(\(.+\))??!?:.+$
- order: 4
- - title: Others
- order: 999
diff --git a/vendor/github.com/gin-contrib/gzip/LICENSE b/vendor/github.com/gin-contrib/gzip/LICENSE
deleted file mode 100644
index a863f57ca..000000000
--- a/vendor/github.com/gin-contrib/gzip/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT 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.
diff --git a/vendor/github.com/gin-contrib/gzip/README.md b/vendor/github.com/gin-contrib/gzip/README.md
deleted file mode 100644
index bb651977c..000000000
--- a/vendor/github.com/gin-contrib/gzip/README.md
+++ /dev/null
@@ -1,169 +0,0 @@
-# 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)
-
-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 with Regex
-
-```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)
- }
-}
-```
-
-### Server Push
-
-```go
-package 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("/stream", func(c *gin.Context) {
- c.Header("Content-Type", "text/event-stream")
- c.Header("Connection", "keep-alive")
- for i := 0; i < 10; i++ {
- fmt.Fprintf(c.Writer, "id: %d\ndata: tick %d\n\n", i, time.Now().Unix())
- c.Writer.Flush()
- time.Sleep(1 * time.Second)
- }
- })
-
- // Listen and Server in 0.0.0.0:8080
- if err := r.Run(":8080"); err != nil {
- log.Fatal(err)
- }
-}
-```
diff --git a/vendor/github.com/gin-contrib/gzip/gzip.go b/vendor/github.com/gin-contrib/gzip/gzip.go
deleted file mode 100644
index 931945a88..000000000
--- a/vendor/github.com/gin-contrib/gzip/gzip.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package gzip
-
-import (
- "bufio"
- "compress/gzip"
- "errors"
- "net"
- "net/http"
-
- "github.com/gin-gonic/gin"
-)
-
-const (
- BestCompression = gzip.BestCompression
- BestSpeed = gzip.BestSpeed
- DefaultCompression = gzip.DefaultCompression
- NoCompression = gzip.NoCompression
- HuffmanOnly = gzip.HuffmanOnly
-)
-
-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)
-}
-
-func (g *gzipWriter) Flush() {
- _ = g.writer.Flush()
- g.ResponseWriter.Flush()
-}
-
-// Fix: https://github.com/mholt/caddy/issues/38
-func (g *gzipWriter) WriteHeader(code int) {
- g.Header().Del("Content-Length")
- g.ResponseWriter.WriteHeader(code)
-}
-
-// Ensure gzipWriter implements the http.Hijacker interface.
-// This will cause a compile-time error if gzipWriter does not implement all methods of the http.Hijacker interface.
-var _ http.Hijacker = (*gzipWriter)(nil)
-
-// Hijack allows the caller to take over the connection from the HTTP server.
-// After a call to Hijack, the HTTP server library will not do anything else with the connection.
-// It becomes the caller's responsibility to manage and close the connection.
-//
-// It returns the underlying net.Conn, a buffered reader/writer for the connection, and an error
-// if the ResponseWriter does not support the Hijacker interface.
-func (g *gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
- hijacker, ok := g.ResponseWriter.(http.Hijacker)
- if !ok {
- return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface")
- }
- return hijacker.Hijack()
-}
diff --git a/vendor/github.com/gin-contrib/gzip/handler.go b/vendor/github.com/gin-contrib/gzip/handler.go
deleted file mode 100644
index 412c8386b..000000000
--- a/vendor/github.com/gin-contrib/gzip/handler.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package gzip
-
-import (
- "compress/gzip"
- "io"
- "net/http"
- "path/filepath"
- "strconv"
- "strings"
- "sync"
-
- "github.com/gin-gonic/gin"
-)
-
-const (
- headerAcceptEncoding = "Accept-Encoding"
- headerContentEncoding = "Content-Encoding"
- headerVary = "Vary"
-)
-
-type gzipHandler struct {
- *config
- gzPool sync.Pool
-}
-
-func isCompressionLevelValid(level int) bool {
- return level == gzip.DefaultCompression ||
- level == gzip.NoCompression ||
- (level >= gzip.BestSpeed && level <= gzip.BestCompression)
-}
-
-func newGzipHandler(level int, opts ...Option) *gzipHandler {
- cfg := &config{
- excludedExtensions: DefaultExcludedExtentions,
- }
-
- // Apply each option to the config
- for _, o := range opts {
- o.apply(cfg)
- }
-
- if !isCompressionLevelValid(level) {
- // For web content, level 4 seems to be a sweet spot.
- level = 4
- }
-
- handler := &gzipHandler{
- config: cfg,
- gzPool: sync.Pool{
- New: func() interface{} {
- gz, _ := gzip.NewWriterLevel(io.Discard, level)
- return gz
- },
- },
- }
- return handler
-}
-
-// Handle is a middleware function for handling gzip compression in HTTP requests and responses.
-// It first checks if the request has a "Content-Encoding" header set to "gzip" and if a decompression
-// function is provided, it will call the decompression function. If the handler is set to decompress only,
-// or if the custom compression decision function indicates not to compress, it will return early.
-// Otherwise, it retrieves a gzip.Writer from the pool, sets the necessary response headers for gzip encoding,
-// and wraps the response writer with a gzipWriter. After the request is processed, it ensures the gzip.Writer
-// is properly closed and the "Content-Length" header is set based on the response size.
-func (g *gzipHandler) Handle(c *gin.Context) {
- if fn := g.decompressFn; fn != nil && strings.Contains(c.Request.Header.Get("Content-Encoding"), "gzip") {
- fn(c)
- }
-
- if g.decompressOnly ||
- (g.customShouldCompressFn != nil && !g.customShouldCompressFn(c)) ||
- (g.customShouldCompressFn == nil && !g.shouldCompress(c.Request)) {
- return
- }
-
- gz := g.gzPool.Get().(*gzip.Writer)
- gz.Reset(c.Writer)
-
- c.Header(headerContentEncoding, "gzip")
- c.Writer.Header().Add(headerVary, headerAcceptEncoding)
- // check ETag Header
- originalEtag := c.GetHeader("ETag")
- if originalEtag != "" && !strings.HasPrefix(originalEtag, "W/") {
- c.Header("ETag", "W/"+originalEtag)
- }
- c.Writer = &gzipWriter{c.Writer, gz}
- defer func() {
- if c.Writer.Size() < 0 {
- // do not write gzip footer when nothing is written to the response body
- gz.Reset(io.Discard)
- }
- _ = gz.Close()
- if c.Writer.Size() > -1 {
- c.Header("Content-Length", strconv.Itoa(c.Writer.Size()))
- }
- g.gzPool.Put(gz)
- }()
- c.Next()
-}
-
-func (g *gzipHandler) shouldCompress(req *http.Request) bool {
- if !strings.Contains(req.Header.Get(headerAcceptEncoding), "gzip") ||
- strings.Contains(req.Header.Get("Connection"), "Upgrade") {
- return false
- }
-
- // Check if the request path is excluded from compression
- extension := filepath.Ext(req.URL.Path)
- if g.excludedExtensions.Contains(extension) ||
- g.excludedPaths.Contains(req.URL.Path) ||
- g.excludedPathesRegexs.Contains(req.URL.Path) {
- return false
- }
-
- return true
-}
diff --git a/vendor/github.com/gin-contrib/gzip/options.go b/vendor/github.com/gin-contrib/gzip/options.go
deleted file mode 100644
index 67607f51b..000000000
--- a/vendor/github.com/gin-contrib/gzip/options.go
+++ /dev/null
@@ -1,270 +0,0 @@
-package gzip
-
-import (
- "compress/gzip"
- "errors"
- "io"
- "net/http"
- "regexp"
- "strings"
-
- "github.com/gin-gonic/gin"
-)
-
-var (
- // DefaultExcludedExtentions is a predefined list of file extensions that should be excluded from gzip compression.
- // These extensions typically represent image files that are already compressed
- // and do not benefit from additional compression.
- DefaultExcludedExtentions = NewExcludedExtensions([]string{
- ".png", ".gif", ".jpeg", ".jpg",
- })
- // ErrUnsupportedContentEncoding is an error that indicates the content encoding
- // is not supported by the application.
- ErrUnsupportedContentEncoding = errors.New("unsupported content encoding")
-)
-
-// Option is an interface that defines a method to apply a configuration
-// to a given config instance. Implementations of this interface can be
-// used to modify the configuration settings of the logger.
-type Option interface {
- apply(*config)
-}
-
-// Ensures that optionFunc implements the Option interface at compile time.
-// If optionFunc does not implement Option, a compile-time error will occur.
-var _ Option = (*optionFunc)(nil)
-
-type optionFunc func(*config)
-
-func (o optionFunc) apply(c *config) {
- o(c)
-}
-
-type config struct {
- excludedExtensions ExcludedExtensions
- excludedPaths ExcludedPaths
- excludedPathesRegexs ExcludedPathesRegexs
- decompressFn func(c *gin.Context)
- decompressOnly bool
- customShouldCompressFn func(c *gin.Context) bool
-}
-
-// WithExcludedExtensions returns an Option that sets the ExcludedExtensions field of the Options struct.
-// Parameters:
-// - args: []string - A slice of file extensions to exclude from gzip compression.
-func WithExcludedExtensions(args []string) Option {
- return optionFunc(func(o *config) {
- o.excludedExtensions = NewExcludedExtensions(args)
- })
-}
-
-// WithExcludedPaths returns an Option that sets the ExcludedPaths field of the Options struct.
-// Parameters:
-// - args: []string - A slice of paths to exclude from gzip compression.
-func WithExcludedPaths(args []string) Option {
- return optionFunc(func(o *config) {
- o.excludedPaths = NewExcludedPaths(args)
- })
-}
-
-// WithExcludedPathsRegexs returns an Option that sets the ExcludedPathesRegexs field of the Options struct.
-// Parameters:
-// - args: []string - A slice of regex patterns to exclude paths from gzip compression.
-func WithExcludedPathsRegexs(args []string) Option {
- return optionFunc(func(o *config) {
- o.excludedPathesRegexs = NewExcludedPathesRegexs(args)
- })
-}
-
-// WithDecompressFn returns an Option that sets the DecompressFn field of the Options struct.
-// Parameters:
-// - decompressFn: func(c *gin.Context) - A function to handle decompression of incoming requests.
-func WithDecompressFn(decompressFn func(c *gin.Context)) Option {
- return optionFunc(func(o *config) {
- o.decompressFn = decompressFn
- })
-}
-
-// WithDecompressOnly is an option that configures the gzip middleware to only
-// decompress incoming requests without compressing the responses. When this
-// option is enabled, the middleware will set the DecompressOnly field of the
-// Options struct to true.
-func WithDecompressOnly() Option {
- return optionFunc(func(o *config) {
- o.decompressOnly = true
- })
-}
-
-// WithCustomShouldCompressFn returns an Option that sets the CustomShouldCompressFn field of the Options struct.
-// Parameters:
-// - fn: func(c *gin.Context) bool - A function to determine if a request should be compressed.
-// The function should return true if the request should be compressed, false otherwise.
-// If the function returns false, the middleware will not compress the response.
-// If the function is nil, the middleware will use the default logic to determine
-// if the response should be compressed.
-//
-// Returns:
-// - Option - An option that sets the CustomShouldCompressFn field of the Options struct.
-//
-// Example:
-//
-// router.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithCustomShouldCompressFn(func(c *gin.Context) bool {
-// return c.Request.URL.Path != "/no-compress"
-// })))
-func WithCustomShouldCompressFn(fn func(c *gin.Context) bool) Option {
- return optionFunc(func(o *config) {
- o.customShouldCompressFn = fn
- })
-}
-
-// Using map for better lookup performance
-type ExcludedExtensions map[string]struct{}
-
-// NewExcludedExtensions creates a new ExcludedExtensions map from a slice of file extensions.
-// Parameters:
-// - extensions: []string - A slice of file extensions to exclude from gzip compression.
-//
-// Returns:
-// - ExcludedExtensions - A map of excluded file extensions.
-func NewExcludedExtensions(extensions []string) ExcludedExtensions {
- res := make(ExcludedExtensions, len(extensions))
- for _, e := range extensions {
- res[e] = struct{}{}
- }
- return res
-}
-
-// Contains checks if a given file extension is in the ExcludedExtensions map.
-// Parameters:
-// - target: string - The file extension to check.
-//
-// Returns:
-// - bool - True if the extension is excluded, false otherwise.
-func (e ExcludedExtensions) Contains(target string) bool {
- _, ok := e[target]
- return ok
-}
-
-type ExcludedPaths []string
-
-// NewExcludedPaths creates a new ExcludedPaths slice from a slice of paths.
-// Parameters:
-// - paths: []string - A slice of paths to exclude from gzip compression.
-//
-// Returns:
-// - ExcludedPaths - A slice of excluded paths.
-func NewExcludedPaths(paths []string) ExcludedPaths {
- return ExcludedPaths(paths)
-}
-
-// Contains checks if a given request URI starts with any of the excluded paths.
-// Parameters:
-// - requestURI: string - The request URI to check.
-//
-// Returns:
-// - bool - True if the URI starts with an excluded path, false otherwise.
-func (e ExcludedPaths) Contains(requestURI string) bool {
- for _, path := range e {
- if strings.HasPrefix(requestURI, path) {
- return true
- }
- }
- return false
-}
-
-type ExcludedPathesRegexs []*regexp.Regexp
-
-// NewExcludedPathesRegexs creates a new ExcludedPathesRegexs slice from a slice of regex patterns.
-// Parameters:
-// - regexs: []string - A slice of regex patterns to exclude paths from gzip compression.
-//
-// Returns:
-// - ExcludedPathesRegexs - A slice of excluded path regex patterns.
-func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs {
- result := make(ExcludedPathesRegexs, len(regexs))
- for i, reg := range regexs {
- result[i] = regexp.MustCompile(reg)
- }
- return result
-}
-
-// Contains checks if a given request URI matches any of the excluded path regex patterns.
-// Parameters:
-// - requestURI: string - The request URI to check.
-//
-// Returns:
-// - bool - True if the URI matches an excluded path regex pattern, false otherwise.
-func (e ExcludedPathesRegexs) Contains(requestURI string) bool {
- for _, reg := range e {
- if reg.MatchString(requestURI) {
- return true
- }
- }
- return false
-}
-
-// DefaultDecompressHandle is a middleware function for the Gin framework that
-// decompresses the request body if it is gzip encoded. It checks if the request
-// body is nil and returns immediately if it is. Otherwise, it attempts to create
-// a new gzip reader from the request body. If an error occurs during this process,
-// it aborts the request with a 400 Bad Request status and the error. If successful,
-// it removes the "Content-Encoding" and "Content-Length" headers from the request
-// and replaces the request body with the decompressed reader.
-//
-// Parameters:
-// - c: *gin.Context - The Gin context for the current request.
-func DefaultDecompressHandle(c *gin.Context) {
- if c.Request.Body == nil {
- return
- }
-
- contentEncodingField := strings.Split(strings.ToLower(c.GetHeader("Content-Encoding")), ",")
- if len(contentEncodingField) == 0 { // nothing to decompress
- c.Next()
-
- return
- }
-
- toClose := make([]io.Closer, 0, len(contentEncodingField))
- defer func() {
- for i := len(toClose); i > 0; i-- {
- toClose[i-1].Close()
- }
- }()
-
- // parses multiply gzips like
- // Content-Encoding: gzip, gzip, gzip
- // allowed by RFC
- for i := 0; i < len(contentEncodingField); i++ {
- trimmedValue := strings.TrimSpace(contentEncodingField[i])
-
- if trimmedValue == "" {
- continue
- }
-
- if trimmedValue != "gzip" {
- // According to RFC 7231, Section 3.1.2.2:
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.2
- // An origin server MAY respond with a status code of 415 (Unsupported
- // Media Type) if a representation in the request message has a content
- // coding that is not acceptable.
- _ = c.AbortWithError(http.StatusUnsupportedMediaType, ErrUnsupportedContentEncoding)
- }
-
- r, err := gzip.NewReader(c.Request.Body)
- if err != nil {
- _ = c.AbortWithError(http.StatusBadRequest, err)
-
- return
- }
-
- toClose = append(toClose, c.Request.Body)
-
- c.Request.Body = r
- }
-
- c.Request.Header.Del("Content-Encoding")
- c.Request.Header.Del("Content-Length")
-
- c.Next()
-}