static

package module
v0.5.12 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

static

Static

Static file server middleware for Hanzo Ingress (Traefik v3).

Serves static files, SPAs, directory listings, and custom error pages directly from the ingress layer — no backend required.

Features

  • Static file serving from any directory
  • SPA mode (fallback to index for client-side routing)
  • Custom index files per directory
  • Directory listing with sortable HTML output
  • Custom 404 error pages
  • Cache-Control headers by file extension
  • gzip on every text response (standalone binary), negotiated per request
  • Hanzo tag injected into every document served
  • Zero dependencies (pure Go stdlib)

Compression

The standalone binary wraps its handler in static.Compress. Text goes out gzipped when the client says it reads gzip; nothing else changes.

Measured on cloud.hanzo.ai's own export, 27 files, one cold load: 1,586,676 B → 440,328 B, 72% off. The document alone is 198,191 → 20,304 (89%), the stylesheet 146,300 → 20,701 (85%).

What it deliberately does not touch: already-compressed types (woff2, png, mp4 — the allowlist is by Content-Type), bodies under 1 KB (a sub-MTU frame costs the same either way and gzip's envelope can make it bigger), Range requests (a range of the compressed stream is not the range that was asked for), and HEAD (no body to compress, and its Content-Length must still describe the resource). Vary: Accept-Encoding is set on every compressible response, including the ones left identity, so shared caches key correctly.

There is no flag. A correct answer does not need to be opted into.

Weight

~360 lines of Go. No external dependencies. Loaded via Yaegi interpreter at runtime — adds negligible overhead to ingress startup.

Configuration

Option Type Default Description
root String . Root directory to serve files from
enableDirectoryListing Boolean false Enable directory browsing
indexFiles Array ["index.html", "index.htm"] Index filenames to try for directories
spaMode Boolean false Redirect all 404s to SPA index
spaIndex String index.html File to serve in SPA mode
errorPage404 String "" Custom 404 page (relative to root)
cacheControl Map {} File extension to Cache-Control value map
key String "" Site publishable key (pk-…). With one, every document served carries the Hanzo tag

Usage

Embedded in Hanzo Ingress (local plugin)

Add to ingress static config:

experimental:
  localPlugins:
    static:
      moduleName: github.com/hanzoai/static

Place the plugin source in plugins-local/src/github.com/hanzoai/static/.

Then use in dynamic config:

http:
  routers:
    site:
      rule: Host(`example.com`)
      service: noop@internal
      middlewares:
        - static-files

  middlewares:
    static-files:
      plugin:
        static:
          root: /var/www/html
Remote plugin
experimental:
  plugins:
    static:
      moduleName: github.com/hanzoai/static
      version: v0.1.0
Analytics

Give the server the site's publishable key and every HTML document it serves goes out carrying the Hanzo tag:

<script defer src="https://api.hanzo.ai/v1/event.js" data-key="pk-…"></script>
http:
  middlewares:
    site:
      plugin:
        static:
          root: /var/www/html
          key: pk-…

Standalone: --key=pk-… or HANZO_KEY=pk-….

The key belongs to the deployment, not to the bundle — the same build is servable by any site, and a key that changes does not need a rebuild. Nothing on the backend is ever modified; the tag exists only in the response.

Anything that is not a small HTML document with a </head> is served byte-for-byte, and so is every document while no key is set. Where a Content-Security-Policy is being sent, https://api.hanzo.ai is added to the script-src and connect-src that need it — only when a tag was actually injected, and only that one origin.

SPA mode (React/Vue/Angular)
http:
  middlewares:
    spa:
      plugin:
        static:
          root: /var/www/app
          spaMode: true
          spaIndex: index.html
          cacheControl:
            ".html": "no-cache"
            ".js": "max-age=31536000"
            ".css": "max-age=31536000"
            "*": "max-age=86400"

Development

make lint    # golangci-lint
make test    # go test -v -cover

License

Apache 2.0 — see LICENSE.

Copyright 2025-2026 Hanzo AI Inc. Based on hhftechnology/statiq (Apache 2.0).

Documentation

Overview

Package static provides a static file server middleware for Hanzo Ingress.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compress added in v0.5.6

func Compress(next http.Handler) http.Handler

Compress wraps a handler so text responses go out gzip-encoded when the client says it can read them.

It is deliberately OUTSIDE the file server rather than inside it: the decision is about the response, not about the file, and every handler mounted here — the directory listing, the 404 page, a future one — gets it for free.

Three requests opt out entirely and are handed the raw writer:

  • No `Accept-Encoding: gzip`. Nothing to negotiate.
  • A `Range` request. http.ServeContent answers those from byte offsets into the identity body; those offsets do not address a compressed stream, and re-deriving them would mean compressing the whole file to serve a slice of it. Ranges stay identity, which is what every CDN and browser expects.
  • A HEAD. It has no body, so there is nothing to compress, and its headers describe the identity representation. Wrapping it was measurably wrong: net/http discards a HEAD body but still counts the bytes offered, so the gzip envelope closing over an empty stream made the server announce `Content-Length: 23` for a 146 KB stylesheet — a number no GET would ever produce and one a health check or a CDN would believe.

func New

func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error)

New creates a new static file server middleware.

Types

type Config

type Config struct {
	// Root directory to serve files from (local filesystem).
	Root string `json:"root,omitempty"`

	// S3 backend configuration (if set, takes precedence over Root).
	S3 *S3Config `json:"s3,omitempty"`

	// EnableDirectoryListing enables directory listing.
	EnableDirectoryListing bool `json:"enableDirectoryListing,omitempty"`

	// IndexFiles is a list of filenames to try when a directory is requested.
	IndexFiles []string `json:"indexFiles,omitempty"`

	// SPAMode redirects all not-found requests to a single page.
	SPAMode bool `json:"spaMode,omitempty"`

	// SPAIndex is the file to serve in SPA mode.
	SPAIndex string `json:"spaIndex,omitempty"`

	// ErrorPage404 is the path to a custom 404 error page.
	ErrorPage404 string `json:"errorPage404,omitempty"`

	// CacheControl sets cache control headers for static files.
	CacheControl map[string]string `json:"cacheControl,omitempty"`

	// Key is the site's publishable key (pk-…). Every document this server sends
	// goes out carrying the Hanzo tag stamped with it; without one, no tag is
	// injected. See tag.go.
	Key string `json:"key,omitempty"`
}

Config holds the static file server middleware configuration.

func CreateConfig

func CreateConfig() *Config

CreateConfig creates the default plugin configuration.

type Handler

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

Handler is a static file server handler.

func (*Handler) GetTracingInformation

func (h *Handler) GetTracingInformation() (string, string)

GetTracingInformation returns the middleware name and type for observability.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves HTTP requests with static files.

type S3Config added in v0.2.0

type S3Config struct {
	// IndexFiles tried for a directory request; defaults to index.html/index.htm.
	IndexFiles []string `json:"indexFiles,omitempty"`
	Endpoint   string   `json:"endpoint,omitempty"`  // S3 endpoint (e.g. s3:9000)
	Bucket     string   `json:"bucket,omitempty"`    // Bucket name
	Region     string   `json:"region,omitempty"`    // Region (default us-east-1)
	AccessKey  string   `json:"accessKey,omitempty"` // Access key ID
	SecretKey  string   `json:"secretKey,omitempty"` // Secret access key
	Prefix     string   `json:"prefix,omitempty"`    // Key prefix
	UseSSL     bool     `json:"useSSL,omitempty"`    // Use HTTPS
}

S3Config holds S3 backend configuration.

type S3FS added in v0.2.0

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

S3FS implements http.FileSystem backed by S3-compatible s3.

func NewS3FS added in v0.2.0

func NewS3FS(_ context.Context, cfg S3Config) (*S3FS, error)

NewS3FS creates an http.FileSystem backed by S3-compatible s3.

func (*S3FS) Open added in v0.2.0

func (s *S3FS) Open(name string) (http.File, error)

Open implements http.FileSystem.

A DIRECTORY REQUEST IS TRANSLATED, NOT REFUSED. On a filesystem `Open("/app/")` yields a directory and the handler then looks inside it for an index; S3 has no directories, so the same intent has to be expressed by asking for the index key itself. Refusing outright — which is what this did — made every static SITE 404 at its own root and at every sub-route, while every ASSET served perfectly. That is exactly why it went unnoticed for so long: the CDN only ever asks for files, and a file is the one case that worked.

Directories

Path Synopsis
cmd
static command

Jump to

Keyboard shortcuts

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