thde.io/rulefiles

GitHub · pkg.go.dev

rulefiles

Go parsers for the _headers and _redirects files of a static site build, the formats popularised by Netlify and Cloudflare Pages.

PackageFilePurposeDocumentation
header_headersResponse header fields for a pathpkg.go.dev/thde.io/rulefiles/header
redirect_redirectsURL redirects, rewrites, and errorspkg.go.dev/thde.io/rulefiles/redirect
go get thde.io/rulefiles@latest

Quick Start

NewHandler reads a rules file and wraps an http.Handler. Handlers compose with header innermost (around the static file server) and redirect outermost, so that header rules apply to the rewritten destination of a redirect:

site, err := header.NewHandler(headersFile, http.FileServerFS(build))
if err != nil {
	return err
}

site, err = redirect.NewHandler(redirectsFile, site)
if err != nil {
	return err
}

For callers that need to inspect or act on rules directly without middleware, both packages also export Parse and Resolve functions. See the package documentation for details.

File Formats

_redirects

_redirects holds one <source> <target> [<status>] rule per line, as documented by Netlify and Cloudflare Pages. The status defaults to 301. A status of 200 rewrites the request internally instead of redirecting. Query parameters of the request are preserved unless the target defines them.

/old/path        /new/path
/docs/:id/*      /articles/:id/:splat  302
/gone            /                     410

_headers

_headers holds an unindented path pattern followed by indented <name>: <value> or ! <name> lines, as documented by Netlify and Cloudflare Pages. All matching rules apply in the order declared; a field set by more than one rule is joined with a comma. Field names are case insensitive.

/*
  X-Robots-Tag: noindex
/static/*
  Cache-Control: public, max-age=31536000, immutable
  ! X-Robots-Tag

Path Patterns & Placeholders

Both formats share pattern syntax:

Differences from Netlify and Cloudflare Pages

Documentation

Full API documentation, options, and examples are available via go doc or pkg.go.dev:

Tests

go test ./...

Both parsers include fuzz tests verifying round-trip encoding and safe resolution:

go test ./redirect -run '^$' -fuzz FuzzResolve
go test ./header -run '^$' -fuzz FuzzResolve