gzip

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2025 License: MIT Imports: 12 Imported by: 656

README

GZIP gin's middleware

Run Tests 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)
  }
}
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.

Jump to

Keyboard shortcuts

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