staticroutes

package
v1.5.8 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 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.

Documentation

Overview

Package staticroutes parses and evaluates the in-repo routing rules of a static site: Netlify style _redirects and _headers files, the app.yaml routes and headers blocks, and the SPA, clean URL and 404 options.

Index

Constants

View Source
const (
	EnvMaxRules       = spec.EnvStaticMaxRules
	EnvMaxHeaderRules = spec.EnvStaticMaxHeaderBlocks
	EnvMaxFileBytes   = "APP_STATIC_ROUTES_MAX_FILE_BYTES"
	EnvMaxValueLen    = "APP_STATIC_ROUTES_MAX_VALUE_LEN"
	EnvMaxProxyRules  = spec.EnvStaticMaxProxyRules
)

Environment variables that tune the caps below. Every one is optional.

View Source
const (
	KindServe    = "serve"
	KindRedirect = "redirect"
	KindNotFound = "not_found"
	// KindProxy means the ingress forwards the request to an app; the file server never serves it.
	KindProxy = "proxy"
)

Decision kinds.

View Source
const (
	SourceRedirects = spec.StaticSourceRedirects
	SourceHeaders   = spec.StaticSourceHeaders
	SourceSpec      = spec.StaticSourceSpec
)

Rule and header sources, shown next to each parsed rule.

View Source
const (
	SeverityError   = spec.StaticSeverityError
	SeverityWarning = spec.StaticSeverityWarning
)

Problem severities.

View Source
const (
	SlashOff    = spec.StaticSlashOff
	SlashAdd    = spec.StaticSlashAdd
	SlashRemove = spec.StaticSlashRemove
)

Trailing slash modes for Options.TrailingSlash.

View Source
const ProxyPrefix = spec.StaticProxyPrefix

ProxyPrefix starts the target of a rule that forwards to an app: app://<name>/<path>.

View Source
const SidecarSuffix = spec.StaticSidecarSuffix

SidecarSuffix names the compiled rules file stored beside a published tree.

View Source
const SourceUI = "ui"

SourceUI labels rules edited in the dashboard; they rank before app.yaml and the files.

Variables

View Source
var ErrImageUnchanged = errors.New("staticroutes: image left unchanged")

ErrImageUnchanged means the original bytes should be served as they are.

Functions

func CompileUI

func CompileUI(redirects []UIRedirect, headers []UIHeader, l Limits) ([]Rule, []HeaderBlock, []LineProblem)

CompileUI validates dashboard rules, returning prepared entries or every problem found.

func DeployHost

func DeployHost(fallbackHost, deployID string) string

DeployHost is the immutable hostname of one deploy: the first 8 letters or digits of its id, two hyphens, then the site's fallback hostname. It returns "" when either part is unusable.

func KeepDeploys

func KeepDeploys() int

KeepDeploys is how many deploys of one Pages site stay on disk and keep their own URL. APP_PAGES_KEEP_DEPLOYS wins, then the older APP_STATIC_KEEP_RELEASES; unset or invalid gives 10, never below 3.

func ParseHeaders

func ParseHeaders(src string, l Limits) ([]HeaderBlock, []Problem)

ParseHeaders parses Netlify _headers syntax; bad lines are reported, never applied.

func ParseRedirects

func ParseRedirects(src string, l Limits) ([]Rule, []Problem)

ParseRedirects parses Netlify _redirects syntax; bad lines are reported, never applied.

func ParseResizeWidth

func ParseResizeWidth(raw string, maxWidth int) int

ParseResizeWidth reads the w query value. It returns 0 when absent or not a positive whole number, and clamps to maxWidth.

func ResizeImage

func ResizeImage(src []byte, width int, lim ImageLimits) ([]byte, string, error)

ResizeImage scales a JPEG or PNG to width keeping the aspect ratio. It checks size and pixel bounds from the header before decoding, and returns ErrImageUnchanged when the file is too big, not an image, or already small.

func SidecarPath

func SidecarPath(rootDir string) string

SidecarPath is where the ruleset of the tree at rootDir is stored.

func SourceKind

func SourceKind(source string) string

SourceKind maps a rule's Source label to file, app.yaml or ui.

func ValidateHeaderBlock

func ValidateHeaderBlock(b *HeaderBlock, l Limits) error

ValidateHeaderBlock checks a block built from app.yaml and prepares it.

func ValidateOptions

func ValidateOptions(o *Options) error

ValidateOptions checks the serving switches.

func ValidateRule

func ValidateRule(r *Rule, l Limits) error

ValidateRule checks a rule and prepares its matcher. It is the single gate for file rules and app.yaml rules alike.

func WriteSidecar

func WriteSidecar(rootDir string, rs *Ruleset) error

WriteSidecar stores rs beside the tree at rootDir, replacing any earlier one.

Types

type Decision

type Decision struct {
	Kind     string     `json:"kind"`
	Status   int        `json:"status"`
	Location string     `json:"location,omitempty"`
	File     string     `json:"file,omitempty"`
	Rule     string     `json:"rule,omitempty"`
	Headers  []HeaderKV `json:"headers"`
	Remove   []string   `json:"remove_headers"`
	Trace    []string   `json:"trace"`
}

Decision is the outcome for one request. File is relative to the site root. Trace lists, in order, every step considered.

type HeaderBlock

type HeaderBlock = spec.StaticHeaderBlock

HeaderBlock applies header changes to matching paths.

type HeaderKV

type HeaderKV = spec.StaticHeaderKV

HeaderKV is one response header.

type ImageLimits

type ImageLimits struct {
	MaxWidth       int
	MaxSourceBytes int
	MaxPixels      int
}

ImageLimits bounds one resize. The caller fills it from runtime settings.

type Input

type Input = spec.StaticInput

Input is what a deploy hands to Compile.

type Limits

type Limits = spec.StaticLimits

Limits caps the size of a site's routing rules.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits are the caps used when no environment override is set.

func LimitsFromEnv

func LimitsFromEnv(lookup func(string) (string, bool)) Limits

LimitsFromEnv applies any valid positive override found through lookup.

type LineProblem

type LineProblem struct {
	Kind    string `json:"kind"`
	Index   int    `json:"index"`
	Message string `json:"message"`
}

LineProblem is one validation failure of a dashboard rule.

type OptionOverrides

type OptionOverrides struct {
	SPA           *bool
	CleanURLs     *bool
	TrailingSlash string
	NotFound      string
}

OptionOverrides replace the serving options a deploy compiled; nil or empty keeps them.

type Options

type Options = spec.StaticServeOptions

Options are the static serving switches.

type Problem

type Problem = spec.StaticProblem

Problem is one validation finding. Line is 0 for spec rules.

type QueryMatch

type QueryMatch = spec.StaticQueryMatch

QueryMatch requires a query parameter.

type Request

type Request struct {
	Method   string
	Path     string
	RawQuery string
}

Request is the part of an HTTP request resolution looks at. Path is the decoded URL path.

type RetainedDeploy

type RetainedDeploy struct {
	Attempt store.DeployAttempt
	Dir     string
}

RetainedDeploy is a past deploy whose files are still on disk.

func RetainedDeploys

func RetainedDeploys(attempts []store.DeployAttempt, svcDir string) []RetainedDeploy

RetainedDeploys picks, newest first and capped at KeepDeploys, the succeeded static deploys of a site whose release directory under svcDir still exists. Rollback records are skipped since they reuse a past tree.

type Rule

type Rule = spec.StaticRule

Rule is one redirect, rewrite or status rule.

type Ruleset

type Ruleset struct {
	spec.StaticRuleset
}

Ruleset is everything compiled for one deploy; Resolve evaluates it.

func Compile

func Compile(in Input, l Limits) (*Ruleset, error)

Compile validates every source and returns the ruleset.

func LoadSidecar

func LoadSidecar(rootDir string) (*Ruleset, error)

LoadSidecar reads the ruleset of the tree at rootDir; none yields nil without an error.

func (*Ruleset) ApplyUI

func (rs *Ruleset) ApplyUI(rules []Rule, blocks []HeaderBlock, o OptionOverrides) error

ApplyUI drops earlier dashboard entries from rs, puts the given ones first and applies the option overrides. Running it twice with the same input is a no-op.

func (*Ruleset) Prepare

func (rs *Ruleset) Prepare() error

Prepare compiles the matchers of a ruleset read back from JSON.

func (*Ruleset) Resolve

func (rs *Ruleset) Resolve(fsys StatFS, req Request) Decision

Resolve applies the documented precedence: explicit rules in order (the first that matches, and, unless forced, only when no file is at the path), then files (exact, clean URL, directory index), then the SPA fallback, then the 404 page.

func (*Ruleset) WithoutProxy

func (rs *Ruleset) WithoutProxy() *Ruleset

WithoutProxy returns a copy of rs with every proxy rule dropped, for hosts that must serve files only (per-deploy preview hosts).

type StatFS

type StatFS interface {
	Stat(name string) (fs.FileInfo, error)
}

StatFS is the one file system call resolution needs; *os.Root satisfies it.

type UIHeader

type UIHeader struct {
	Path   string            `json:"path"`
	Set    map[string]string `json:"set,omitempty"`
	Remove []string          `json:"remove,omitempty"`
}

UIHeader is one dashboard header block.

type UIRedirect

type UIRedirect struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Status int    `json:"status,omitempty"`
	Force  bool   `json:"force,omitempty"`
}

UIRedirect is one dashboard redirect rule.

Jump to

Keyboard shortcuts

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