Skip to content

goflash/compression

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Compression middleware for the GoFlash web framework

Features

  • Multiple compression algorithms: Gzip (stdlib) and Brotli (github.com/andybalholm/brotli)
  • Unified compression middleware: Automatic fallback based on client support
  • Individual compression middlewares: Use specific algorithms when needed
  • High performance: Pooled compression writers to minimize allocations
  • Flexible configuration: Per-route compression levels and minimum size thresholds
  • Extensible design: Easy to add new compression algorithms via the CompressionProvider interface
  • Zero-allocation hot paths: Optimized for high-throughput scenarios
  • Graceful fallbacks: Handles missing dependencies and unsupported compression types

Installation

go get github.com/goflash/compression

Go version: requires Go 1.23+. The module sets go 1.23 and can be used with newer Go versions.

Quick start

Basic usage with default gzip compression

package main

import (
    "log"
    "net/http"

    "github.com/goflash/compression"
    "github.com/goflash/flash/v2"
)

func main() {
    app := flash.New()

    // Global gzip compression with defaults
    app.Use(compression.Gzip())

    // Define a simple route
    app.GET("/", func(c flash.Ctx) error {
        return c.String(http.StatusOK, "Hello, compressed world!")
    })

    log.Fatal(http.ListenAndServe(":8080", app))
}

Unified compression with automatic fallback

package main

import (
    "log"
    "net/http"

    "github.com/goflash/compression"
    "github.com/goflash/flash/v2"
)

func main() {
    app := flash.New()

    // Prefer brotli, fallback to gzip
    app.Use(compression.Compress(compression.UnifiedConfig{
        Types: []compression.CompressionType{
            compression.BrotliCompression,
            compression.GzipCompression,
        },
        Level:   6,    // balanced performance
        MinSize: 1024, // only compress responses > 1KB
    }))

    app.GET("/api/data", func(c flash.Ctx) error {
        return c.JSON(map[string]string{"message": "This will be compressed!"})
    })

    log.Fatal(http.ListenAndServe(":8080", app))
}

Configuration

Compression Types

  • Gzip (compression.GzipCompression): Universal support, good compression ratios
  • Brotli (compression.BrotliCompression): Better compression ratios, modern browsers only

Compression Levels

  • Gzip: 1-9 (1=fastest, 9=best compression)
  • Brotli: 0-11 (0=fastest, 11=best compression)
  • Default: 6 (balanced performance)

Per-route compression

// High compression for static assets
app.GET("/static/*", staticHandler, compression.Gzip(compression.CompressionConfig{
    Level:   9,   // maximum compression
    MinSize: 256, // compress even small files
}))

// Fast compression for API responses
app.GET("/api/*", apiHandler, compression.Compress(compression.UnifiedConfig{
    Types:   []compression.CompressionType{compression.GzipCompression},
    Level:   3,    // fast compression
    MinSize: 512,  // reasonable threshold
}))

Examples

The examples/ directory contains three comprehensive examples:

  • examples/basic: Simple gzip compression setup
  • examples/advanced: Unified compression with multiple algorithms and static file serving
  • examples/complex: Advanced usage patterns with different compression strategies per route

Run any example locally:

cd examples/basic
go run .

Then test with curl:

# Test gzip compression
curl -H 'Accept-Encoding: gzip' http://localhost:8080/

# Test brotli compression
curl -H 'Accept-Encoding: br' http://localhost:8080/

# Test automatic fallback
curl -H 'Accept-Encoding: br, gzip' http://localhost:8080/

Extensibility

The package is designed for extensibility. New compression algorithms can be added by implementing the CompressionProvider interface:

type CompressionProvider interface {
    NewWriter(w io.Writer, level int) (io.WriteCloser, error)
    GetWriter(level int, w io.Writer) (*CompressionWriter, error)
    CompressionType() CompressionType
    IsSupported() bool
}

Performance

  • Pooled writers: Compression writers are pooled per algorithm and level to minimize allocations
  • Lazy initialization: Compression writers are created only when needed
  • Automatic cleanup: Writers are returned to pools via defer statements
  • Zero-copy paths: Optimized for scenarios where compression isn't needed
  • Content-Length handling: Proper header management for optimal HTTP performance

Testing

Run tests with coverage:

./scripts/coverage.sh

The package includes comprehensive tests covering:

  • All compression algorithms
  • Edge cases (HEAD requests, small responses, error conditions)
  • Integration with GoFlash middleware system
  • Performance characteristics

Browser Support

Gzip

  • Universal support (all modern browsers and HTTP clients)

Brotli

  • Chrome 50+ (2016)
  • Firefox 44+ (2016)
  • Safari 11+ (2017)
  • Edge 15+ (2017)

Versioning and compatibility

  • Module path: github.com/goflash/compression
  • Requires Go 1.23+
  • Compatible with GoFlash v2.0.0+

Contributing

Issues and PRs are welcome! Please:

  1. Run tests before submitting: ./scripts/coverage.sh
  2. Follow Go conventions and add comprehensive documentation
  3. Include tests for new features
  4. Update examples if adding new functionality

License

MIT

About

Compression middleware for the GoFlash web framework

Topics

Resources

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published