gzip

package module
v1.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 13 Imported by: 834

README

GZIP gin's middleware

Run Tests Trivy Security Scan codecov Go Report Card GoDoc

Gin middleware to enable GZIP support.

Usage

Download and install it:

go get github.com/gin-contrib/gzip

Import it in your code:

import "github.com/gin-contrib/gzip"

Canonical example:

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)
  }
}
Compress only when response meets minimum byte size
package main

import (
	"log"
	"net/http"
	"strconv"
	"strings"

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

func main() {
	r := gin.Default()
	r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithMinLength(2048)))
	r.GET("/ping", func(c *gin.Context) {
		sizeStr := c.Query("size")
		size, _ := strconv.Atoi(sizeStr)
		c.String(http.StatusOK, strings.Repeat("a", size))
	})

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

Test with curl:

curl -i --compressed 'http://localhost:8080/ping?size=2047'
curl -i --compressed 'http://localhost:8080/ping?size=2048'

Notes:

  • If a "Content-Length" header is set, that will be used to determine whether to compress based on the given min length.
  • If no "Content-Length" header is set, a buffer is used to temporarily store writes until the min length is met or the request completes.
    • Setting a high min length will result in more buffering (2048 bytes is a recommended default for most cases)
    • The handler performs optimizations to avoid unnecessary operations, such as testing if len(data) exceeds min length before writing to the buffer, and reusing buffers between requests.
Customized Excluded Extensions
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
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
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
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)
  }
}

Documentation

Index

Constants

View Source
const (
	BestCompression    = gzip.BestCompression
	BestSpeed          = gzip.BestSpeed
	DefaultCompression = gzip.DefaultCompression
	NoCompression      = gzip.NoCompression
	HuffmanOnly        = gzip.HuffmanOnly
)

Variables

View Source
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")
)

Functions

func DefaultDecompressHandle added in v0.0.2

func DefaultDecompressHandle(c *gin.Context)

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 Gzip

func Gzip(level int, options ...Option) gin.HandlerFunc

Types

type ExcludedExtensions added in v0.0.2

type ExcludedExtensions map[string]struct{}

Using map for better lookup performance

func NewExcludedExtensions added in v0.0.2

func NewExcludedExtensions(extensions []string) ExcludedExtensions

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 (ExcludedExtensions) Contains added in v0.0.2

func (e ExcludedExtensions) Contains(target string) bool

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.

type ExcludedPathesRegexs added in v0.0.2

type ExcludedPathesRegexs []*regexp.Regexp

func NewExcludedPathesRegexs added in v0.0.2

func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs

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 (ExcludedPathesRegexs) Contains added in v0.0.2

func (e ExcludedPathesRegexs) Contains(requestURI string) bool

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.

type ExcludedPaths added in v0.0.2

type ExcludedPaths []string

func NewExcludedPaths added in v0.0.2

func NewExcludedPaths(paths []string) ExcludedPaths

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 (ExcludedPaths) Contains added in v0.0.2

func (e ExcludedPaths) Contains(requestURI string) bool

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.

type Option added in v0.0.2

type Option interface {
	// contains filtered or unexported methods
}

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.

func WithCustomShouldCompressFn added in v1.2.0

func WithCustomShouldCompressFn(fn func(c *gin.Context) bool) Option

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 WithDecompressFn added in v0.0.2

func WithDecompressFn(decompressFn func(c *gin.Context)) Option

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 WithDecompressOnly added in v1.2.0

func WithDecompressOnly() Option

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 WithExcludedExtensions added in v0.0.2

func WithExcludedExtensions(args []string) Option

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 WithExcludedPaths added in v0.0.2

func WithExcludedPaths(args []string) Option

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 WithExcludedPathsRegexs added in v0.0.2

func WithExcludedPathsRegexs(args []string) Option

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 WithMinLength added in v1.2.6

func WithMinLength(minLength int) Option

WithMinLength returns an Option that sets the minLength field of the Options struct. Parameters:

  • minLength: int - The minimum length of the response body (in bytes) to trigger gzip compression. If the response body is smaller than this length, it will not be compressed. This option is useful for avoiding the overhead of compression on small responses, especially since gzip compression actually increases the size of small responses. 2048 is a recommended value for most cases. The minLength value must be non-negative; negative values will cause undefined behavior.

Note that specifying this option does not override other options. If a path has been excluded (eg through WithExcludedPaths), it will continue to be excluded.

Returns:

  • Option - An option that sets the MinLength field of the Options struct.

Example:

router.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithMinLength(2048)))

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL