Documentation
¶
Overview ¶
Package statute is a config-as-code reverse proxy framework.
Configurations are written as Go values, validated and resolved at startup, then executed by the runtime. There is no runtime config file, no hot reload, and no module loader — the binary IS the configuration.
See the examples directory for canonical usage.
Index ¶
- Variables
- func Cache(ttl string) *cacheMW
- func Compress(algos ...CompressAlgo) *compressMW
- func ETag() *etagMW
- func Export(cfg Config, w io.Writer) error
- func JSONLog(dest LogWriter) *jsonLog
- func Main(cfg Config)
- func OTLP(endpoint string) *otlpTracing
- func RateLimit(rate string) *rateLimitMW
- func Resolve(cfg Config) (*resolved.Config, error)
- func Retry(max int, opts ...RetryOption) *retryMW
- func Run(cfg Config)
- func Timeout(dur string) *timeoutMW
- type AccessLog
- type AutoTLSConfig
- type Backend
- type CompressAlgo
- type Config
- type Defaults
- type HealthCheck
- type Listener
- type ListenerOption
- type Listeners
- type LogWriter
- type Metrics
- type Middleware
- type Observability
- type Pool
- type RateLimitKey
- type RetryOption
- type Route
- type Routes
- type Shutdown
- type StaticTLSConfig
- type Strategy
- type Tracing
- type Transport
- type Upstreams
Constants ¶
This section is empty.
Variables ¶
var Stderr = LogWriter{/* contains filtered or unexported fields */}
Stderr writes logs to process stderr.
var Stdout = LogWriter{/* contains filtered or unexported fields */}
Stdout writes logs to process stdout.
Functions ¶
func Cache ¶
func Cache(ttl string) *cacheMW
Cache returns a response-cache middleware with the given TTL.
func Compress ¶
func Compress(algos ...CompressAlgo) *compressMW
Compress returns a response-compression middleware that negotiates one of the listed algorithms based on the request's Accept-Encoding header.
func ETag ¶
func ETag() *etagMW
ETag returns a middleware that adds ETag headers to static file responses and serves 304 Not Modified for matching If-None-Match requests.
func Export ¶
Export validates and resolves the surface configuration, then writes the canonical resolved schema as JSON. Useful for diffing deployments and snapshotting in CI without starting a server.
func JSONLog ¶
func JSONLog(dest LogWriter) *jsonLog
JSONLog returns a structured (JSON) access log writing to the given destination. By default every request is logged; use Sample to record only a fraction of requests at high traffic volumes.
func Main ¶
func Main(cfg Config)
Main is a thin CLI wrapper around Run, Export, and a validate-only mode. It parses the standard process arguments and dispatches:
-export Write the resolved configuration as JSON to stdout and exit. -validate Validate the configuration and exit. Prints "ok" on success. (no flag) Equivalent to Run.
Programs that want a clean entry point without flag handling can call Run directly.
func OTLP ¶
func OTLP(endpoint string) *otlpTracing
OTLP configures distributed tracing via OTLP/gRPC to the given collector endpoint (for example "otel-collector:4317"). Spans are produced for every incoming request with HTTP semantic conventions, and W3C trace context is propagated to upstream backends.
func RateLimit ¶
func RateLimit(rate string) *rateLimitMW
RateLimit returns a rate-limit middleware. The rate string is of the form "N/unit" where unit is one of s, min, h. For example "100/min".
func Resolve ¶
Resolve validates the surface configuration, fills defaults, and produces the canonical resolved schema. Resolve is pure: it does not touch the network, the filesystem, or process state.
func Retry ¶
func Retry(max int, opts ...RetryOption) *retryMW
Retry returns a retry middleware with the given maximum attempts and options.
Types ¶
type AccessLog ¶
type AccessLog interface {
// contains filtered or unexported methods
}
AccessLog is a marker for an access log destination.
type AutoTLSConfig ¶
type AutoTLSConfig struct {
Domains []string
// contains filtered or unexported fields
}
AutoTLSConfig declares ACME-managed TLS material.
func AutoTLS ¶
func AutoTLS(domains ...string) *AutoTLSConfig
AutoTLS configures ACME auto-provisioning for the given domains.
func (*AutoTLSConfig) CloudflareDNS01 ¶
func (a *AutoTLSConfig) CloudflareDNS01(apiToken string) *AutoTLSConfig
CloudflareDNS01 switches the ACME challenge from HTTP-01 to DNS-01 using Cloudflare's DNS API. Required for wildcard certificates and useful when :80 is not reachable from the public internet (private networks, Cloudflare-only origins, etc.).
The token must be a Cloudflare API Token (not the legacy Global API Key) with the Zone.DNS:Edit permission for the zone(s) covering the listener's domains. Generate one at https://dash.cloudflare.com/profile/api-tokens.
The zone is auto-discovered from each domain by walking the DNS labels against the account's zone list. Use Zone() to pin a specific zone ID and skip discovery.
Returns the parent AutoTLSConfig so the call chain remains a single ListenerOption value usable as an argument to HTTPS.
func (*AutoTLSConfig) Email ¶
func (a *AutoTLSConfig) Email(email string) *AutoTLSConfig
Email sets the contact email registered with the ACME directory.
func (*AutoTLSConfig) Storage ¶
func (a *AutoTLSConfig) Storage(path string) *AutoTLSConfig
Storage sets the on-disk path where issued certificates and ACME state are persisted. Required for production use.
func (*AutoTLSConfig) Zone ¶
func (a *AutoTLSConfig) Zone(id string) *AutoTLSConfig
Zone pins the Cloudflare zone ID for DNS-01 challenges. Must be called after CloudflareDNS01. When unset the zone is discovered by querying Cloudflare for the zone whose name is a suffix of each domain.
type Backend ¶
type Backend struct {
// Address is the host:port of the backend.
Address string
// Weight is the relative weight for weighted strategies. Defaults to 1.
Weight int
// Backup is true for failover-only backends; they receive traffic only
// when all primary backends are unhealthy.
Backup bool
}
Backend is a single upstream target.
type CompressAlgo ¶
type CompressAlgo int
CompressAlgo identifies a content-encoding algorithm.
const ( // Gzip compression. Gzip CompressAlgo = iota // Brotli compression. Brotli )
func (CompressAlgo) String ¶
func (a CompressAlgo) String() string
String returns the canonical name of the algorithm.
type Config ¶
type Config struct {
Listeners Listeners
Upstreams Upstreams
Routes Routes
Defaults Defaults
Observability Observability
Shutdown Shutdown
}
Config is the top-level surface configuration.
type Defaults ¶
type Defaults struct {
// ReadHeaderTimeout caps how long a client may take to send the request
// headers. The Go standard library has no default; setting this is the
// primary mitigation for Slowloris denial-of-service.
ReadHeaderTimeout string
// ReadTimeout caps the entire request read, including body. Use with care
// for streaming and long-poll endpoints.
ReadTimeout string
// WriteTimeout caps how long the server may take to write the response.
WriteTimeout string
// IdleTimeout caps how long an idle keep-alive connection may sit between
// requests before being closed.
IdleTimeout string
// MaxHeaderBytes caps the size of the request header block. Defaults to
// the Go standard library default of 1MB when unset.
MaxHeaderBytes int
}
Defaults sets the conservative production baseline for all listeners. Routes may override individual values via middleware.
type HealthCheck ¶
type HealthCheck struct {
Path string // HTTP path to probe; empty disables active health checks
Interval string // how often to probe; e.g. "10s"
Timeout string // probe timeout; e.g. "2s"
Healthy int // consecutive successes to mark healthy; defaults to 2
Unhealthy int // consecutive failures to mark unhealthy; defaults to 3
}
HealthCheck configures active health checks against backends.
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Listener is a surface listener declaration. Construct via HTTP or HTTPS.
func HTTPS ¶
func HTTPS(addr string, opts ...ListenerOption) *Listener
HTTPS starts an HTTPS listener declaration on the given address. Options configure TLS material, HTTP/2, and HTTP/3.
func (*Listener) RedirectTo ¶
RedirectTo turns this listener into a permanent redirect to the named scheme. The listener will not serve content beyond the redirect.
type ListenerOption ¶
type ListenerOption interface {
// contains filtered or unexported methods
}
ListenerOption configures an HTTPS listener.
func BehindCloudflare ¶
func BehindCloudflare() ListenerOption
BehindCloudflare marks the listener as sitting behind a Cloudflare proxy. This affects two things:
First, when AutoTLS is configured on the listener, the TLS-ALPN-01 challenge is suppressed (the "acme-tls/1" entry is dropped from ALPN). Cloudflare terminates TLS at its edge and does not forward custom ALPN protocols, so TLS-ALPN-01 cannot succeed. Provisioning falls back to HTTP-01, which is served by the redirect listener on :80 — Cloudflare proxies that path transparently provided "Always Use HTTPS" is disabled for /.well-known/acme-challenge/*.
Second, the request handling path trusts the CF-Connecting-IP and True-Client-IP headers as the originating client address. Other proxy headers (X-Forwarded-For) remain available but Cloudflare's are preferred because they are populated by the proxy and not user-controllable.
func HTTP2 ¶
func HTTP2() ListenerOption
HTTP2 enables HTTP/2 on the listener. Required for h2 ALPN negotiation.
func HTTP3 ¶
func HTTP3(addr string) ListenerOption
HTTP3 enables HTTP/3 (QUIC) on the listener at the given UDP address. The addr should typically match the HTTPS port suffixed with /udp, for example ":443/udp".
type LogWriter ¶
type LogWriter struct {
// contains filtered or unexported fields
}
LogWriter identifies a destination for structured logs.
type Metrics ¶
type Metrics interface {
// contains filtered or unexported methods
}
Metrics is a marker for a metrics endpoint configuration.
func Prometheus ¶
Prometheus exposes process and request metrics on the given address and path, formatted in the Prometheus exposition format.
type Middleware ¶
type Middleware interface {
// contains filtered or unexported methods
}
Middleware is a marker interface for surface middleware values. Concrete middleware constructors return values that satisfy this interface.
type Observability ¶
Observability bundles the logging, metrics, and tracing configuration.
type Pool ¶
type Pool struct {
Backends []Backend
Strategy Strategy
HealthCheck HealthCheck
Transport Transport
}
Pool is the surface upstream pool definition.
type RateLimitKey ¶
type RateLimitKey int
RateLimitKey selects what attribute of the request a rate limit is keyed on.
const ( // ClientIP keys the rate limiter on the client's IP address. ClientIP RateLimitKey = iota // HostHeader keys the rate limiter on the Host header. HostHeader )
func (RateLimitKey) String ¶
func (k RateLimitKey) String() string
String returns the canonical name of the key.
type RetryOption ¶
type RetryOption interface {
// contains filtered or unexported methods
}
RetryOption configures the Retry middleware.
func OnStatus ¶
func OnStatus(codes ...int) RetryOption
OnStatus retries when the upstream returns any of the given status codes.
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route is a surface route declaration. Construct via Match.
func Match ¶
Match begins a route declaration matching the given path pattern. Patterns support a trailing /* wildcard.
func (*Route) With ¶
func (r *Route) With(mws ...Middleware) *Route
With attaches middleware to the route. Middleware runs in declaration order before the upstream proxy or static file handler.
type Routes ¶
type Routes []*Route
Routes is the list of route declarations, matched in declaration order.
type Shutdown ¶
type Shutdown struct {
// GracePeriod is the maximum time the server will wait for in-flight
// requests to finish before forcibly closing connections. e.g. "30s".
GracePeriod string
// DrainListeners closes listeners (stops accepting new connections)
// before waiting for in-flight requests. Recommended for production.
DrainListeners bool
}
Shutdown configures graceful shutdown behaviour.
type StaticTLSConfig ¶
StaticTLSConfig declares pre-provisioned TLS material.
func StaticTLS ¶
func StaticTLS(certFile, keyFile string) *StaticTLSConfig
StaticTLS configures TLS using a static certificate and key on disk.
type Strategy ¶
type Strategy int
Strategy selects how a request is routed across the backends in a pool.
const ( // RoundRobin distributes requests evenly across backends in declaration order. RoundRobin Strategy = iota // LeastConnections sends each request to the backend with the fewest in-flight requests. LeastConnections // IPHash routes requests from the same client IP to the same backend (consistent hash). IPHash // Weighted distributes requests proportionally to each backend's Weight. Weighted )
type Tracing ¶
type Tracing interface {
// contains filtered or unexported methods
}
Tracing is a marker for a distributed-tracing exporter configuration.
Source Files
¶
- accesslog.go
- autotls.go
- cache.go
- cloudflare.go
- cloudflare_api.go
- compress.go
- defaults.go
- dns01.go
- etag.go
- export.go
- healthcheck.go
- http3.go
- listeners.go
- metrics.go
- middleware.go
- observability.go
- otel.go
- pprof.go
- ratelimit.go
- resolve.go
- responsebuffer.go
- retry.go
- routes.go
- server.go
- shutdown.go
- statute.go
- strategies.go
- upstreams.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
cloudflare
command
Example: a statute deployment fronted by Cloudflare with origin AutoTLS.
|
Example: a statute deployment fronted by Cloudflare with origin AutoTLS. |
|
cloudflare-wildcard
command
Example: wildcard certificate via Cloudflare DNS-01.
|
Example: wildcard certificate via Cloudflare DNS-01. |
|
http-only
command
|
|
|
Package resolved is the canonical, fully-validated schema that the statute runtime operates on.
|
Package resolved is the canonical, fully-validated schema that the statute runtime operates on. |