compress

package module
v1.5.6 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package compress provides transparent response compression middleware for celeris.

It negotiates an encoding from the Accept-Encoding request header and compresses 2xx responses on the fly. Supported encodings are zstd, brotli ("br"), gzip, and deflate; the default server-side priority is zstd > br > gzip. Deflate is supported but opt-in (add "deflate" to Config.Encodings) because it is superseded by gzip.

New returns the middleware; call it with no arguments for defaults (MinLength 256, the default encoding list and excluded content types) or pass a Config to tune behavior:

server.Use(compress.New())

Per-encoding levels are set via Config.GzipLevel, Config.BrotliLevel, Config.ZstdLevel, and Config.DeflateLevel, each accepting a Level (LevelDefault, LevelFastest, LevelBest, LevelNone) or an integer in the encoding's valid range. Use Config.Skip, Config.SkipPaths, Config.MinLength, and Config.ExcludedContentTypes to control what gets compressed.

The middleware buffers the response body before compressing, so it does not apply to handlers that use celeris.Context.StreamWriter. For streaming endpoints, wrap a StreamWriter with NewCompressedStream (gzip or brotli only), or bypass compression with Config.Skip.

This package is a separate Go module (middleware/compress/go.mod); import it as "github.com/goceleris/celeris/middleware/compress".

Documentation

Full guides and examples: https://goceleris.dev/docs/middleware-content

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(config ...Config) celeris.HandlerFunc

New creates a compress middleware with the given config.

Example
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	// Default: zstd > brotli > gzip, MinLength 256.
	//   server.Use(compress.New())
	_ = compress.New()
}
Example (CustomMinLength)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	_ = compress.New(compress.Config{
		MinLength: 1024,
	})
}
Example (Deflate)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	// Opt-in to deflate for legacy client support. Deflate is not
	// included in the default Encodings list.
	_ = compress.New(compress.Config{
		Encodings:    []string{"zstd", "br", "gzip", "deflate"},
		DeflateLevel: compress.LevelDefault,
	})
}
Example (ExcludedContentTypes)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	_ = compress.New(compress.Config{
		ExcludedContentTypes: []string{
			"image/",
			"video/",
			"audio/",
			"application/octet-stream",
		},
	})
}
Example (GzipOnly)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	_ = compress.New(compress.Config{
		Encodings: []string{"gzip"},
		GzipLevel: compress.LevelFastest,
	})
}
Example (NoCompression)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	// LevelNone stores data without compression (useful for testing).
	_ = compress.New(compress.Config{
		Encodings: []string{"gzip"},
		GzipLevel: compress.LevelNone,
	})
}
Example (Skip)
package main

import (
	"strings"

	"github.com/goceleris/celeris"
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	// Dynamic skip: bypass compression for WebSocket upgrades and
	// streaming download endpoints.
	_ = compress.New(compress.Config{
		Skip: func(c *celeris.Context) bool {
			if c.Header("upgrade") == "websocket" {
				return true
			}
			return strings.HasPrefix(c.Path(), "/download/")
		},
	})
}
Example (SkipPaths)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	_ = compress.New(compress.Config{
		SkipPaths: []string{"/health", "/metrics", "/debug/pprof"},
	})
}
Example (ZstdLevel)
package main

import (
	"github.com/goceleris/celeris/middleware/compress"
)

func main() {
	// Use SpeedBestCompression (level 4) for zstd.
	_ = compress.New(compress.Config{
		Encodings: []string{"zstd"},
		ZstdLevel: compress.LevelBest,
	})
}

Types

type CompressedStream

type CompressedStream struct {
	// contains filtered or unexported fields
}

CompressedStream wraps a celeris.StreamWriter with on-the-fly compression. The caller obtains a StreamWriter from celeris.Context.StreamWriter, then wraps it with NewCompressedStream for transparent compression.

Supported encodings: "gzip" and "br" (brotli). Zstd uses EncodeAll (batch) and is not suitable for streaming; use the buffered middleware (New) for zstd.

Unlike the buffered compress middleware, CompressedStream does not support the expansion guard or MinLength threshold — the response is compressed unconditionally.

func NewCompressedStream

func NewCompressedStream(sw *celeris.StreamWriter, encoding string, opts ...StreamOption) *CompressedStream

NewCompressedStream wraps sw with compression for the given encoding. Supported encodings: "gzip", "br". Returns nil if the encoding is unsupported or sw is nil.

Optional StreamOption values configure compression levels. Without options, library defaults are used (gzip level 6, brotli level 6).

Content-Encoding and Vary headers are set automatically on CompressedStream.WriteHeader. Any Content-Length in the user headers is stripped (streaming responses use chunked transfer encoding).

func (*CompressedStream) Close

func (cs *CompressedStream) Close() error

Close closes the compressor (writes final bytes/trailer) and the underlying StreamWriter. Safe to call multiple times; subsequent calls are no-ops.

func (*CompressedStream) Flush

func (cs *CompressedStream) Flush() error

Flush flushes the compressor and the underlying StreamWriter.

func (*CompressedStream) Write

func (cs *CompressedStream) Write(data []byte) (int, error)

Write compresses data and sends it to the underlying StreamWriter.

func (*CompressedStream) WriteHeader

func (cs *CompressedStream) WriteHeader(status int, headers [][2]string) error

WriteHeader sends the status line and headers with Content-Encoding and Vary added automatically. Any Content-Length header is stripped because streaming responses use chunked transfer encoding. Must be called once before Write.

type Config

type Config struct {
	// Skip defines a function to skip this middleware for certain requests.
	Skip func(c *celeris.Context) bool

	// SkipPaths lists paths to skip from compression (exact match).
	SkipPaths []string

	// MinLength is the minimum response body size (in bytes) required for
	// compression. Responses smaller than this are sent uncompressed.
	// Default: 256 (when no Config is passed to New).
	// Set to 0 to compress all non-empty responses regardless of size.
	MinLength int

	// Encodings lists the supported encodings in server-side priority order.
	// Supported values: "zstd", "br", "gzip", "deflate".
	// Default: ["zstd", "br", "gzip"] (deflate is opt-in only).
	Encodings []string

	// GzipLevel sets the gzip compression level.
	// Default: LevelDefault (0 = library default, gzip level 6).
	// Use LevelNone (-1) for store-only (no compression).
	GzipLevel Level

	// BrotliLevel sets the brotli compression level.
	// Default: LevelDefault (0 = library default, brotli level 6).
	// Use LevelNone (-1) for no compression.
	BrotliLevel Level

	// ZstdLevel sets the zstd compression level.
	// Default: LevelDefault (0 = library default).
	// Use LevelNone (-1) for no compression.
	ZstdLevel Level

	// DeflateLevel sets the deflate (raw DEFLATE, RFC 1951) compression level.
	// Deflate is a legacy encoding; prefer gzip, brotli, or zstd for new
	// deployments. Add "deflate" to Encodings to enable it (not included by
	// default). Default: LevelDefault (0 = library default, flate.DefaultCompression).
	DeflateLevel Level

	// ExcludedContentTypes lists content-type prefixes that should not be
	// compressed. Set to an empty slice to disable all content-type exclusions.
	// Default: ["image/", "video/", "audio/"].
	ExcludedContentTypes []string
}

Config defines the compress middleware configuration.

type Level

type Level int

Level controls the compression level for a given encoding. The zero value (LevelDefault) selects the library default, which is idiomatic Go: a zero-value Config uses sensible defaults for all levels.

const (
	// LevelDefault uses the library default compression level.
	// It is intentionally the zero value so that an unset field in Config
	// falls through to the library default.
	LevelDefault Level = 0
	// LevelNone stores data without compression (gzip level 0, brotli level 0).
	LevelNone Level = -1
	// LevelBest is a sentinel that resolves to the encoding-specific maximum:
	// gzip -> 9, brotli -> 11, zstd -> SpeedBestCompression (4).
	LevelBest Level = -2
	// LevelFastest uses the fastest (lowest) compression level.
	LevelFastest Level = 1
)

type StreamOption

type StreamOption func(*streamConfig)

StreamOption configures streaming compression.

func WithBrotliLevel

func WithBrotliLevel(level Level) StreamOption

WithBrotliLevel sets the brotli compression level for streaming. Default: 6.

func WithGzipLevel

func WithGzipLevel(level Level) StreamOption

WithGzipLevel sets the gzip compression level for streaming. Default: gzip.DefaultCompression (-1).

Jump to

Keyboard shortcuts

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