fh

package module
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 63 Imported by: 0

README

fh — Zero-Dependency Go Web Framework

fh is a standalone, high-performance HTTP/1.1 + HTTP/2 + WebSocket web framework for Go with no third-party dependencies beyond golang.org/x/crypto (used only for optional OCSP stapling and ACME certificate automation). It implements HTTP parsing, routing, HTTP/2 framing, HPACK, and WebSocket protocols from scratch — no wrappers around net/http or fasthttp.

Full reference documentation lives in docs/.

Features

  • Minimal dependencies — the Go standard library plus golang.org/x/crypto, both optional (OCSP stapling, ACME)
  • HTTP/1.1 — full request/response parsing, chunked transfer, trailers
  • HTTP/2 — TLS ALPN, optional h2c prior knowledge/upgrade, stream multiplexing, flow control, RFC 8441 extended CONNECT
  • WebSocket — RFC 6455 server implementation with EventHub pub/sub layer, transparently served over HTTP/1.1 or HTTP/2
  • Trie-based router — radix tree with named (:param) and wildcard (*wild) parameters
  • Codec system — pluggable body parsers for JSON, XML, form, multipart, CSV, NDJSON, text, binary
  • 70+ built-in middleware packages — see Middleware below
  • Typed endpoints & OpenAPI 3.1 — generic request/response handlers with auto-generated specs
  • Reliability layer — request journaling, idempotency, durable async queue, outbox/inbox, DLQ
  • Compliance layer — Business/Professional/Enterprise/Security profiles, audit ledger, route security metadata
  • Opt-in fail-closed baseline — fh.WithSecureByDefault(true) bounds every protocol input, enables strict parsing, recovery, redaction, and hardened response headers. Neither this nor fh.NewProduction() adds authentication, CSRF protection, rate limiting, or a Host allow-list — see Production Readiness
  • Template engine — agnostic interface, any engine implementing Render(w, name, data, layout...)
  • Static file serving — direct streaming, range requests, streaming gzip, precompressed Brotli/gzip, cache control
  • Streaming uploads — opt-in incremental HTTP/1 body consumption with bounded draining and trailer support
  • Graceful shutdown — app.ServeContext(ctx, listener), app.ListenContext(ctx, addr), app.ListenUnixContext(ctx, path), app.ShutdownWithContext(ctx), or app.ListenWithGracefulShutdown(addr)
  • Graceful TLS shutdown — app.ListenTLSWithGracefulShutdown(addr, certFile, keyFile)
  • Pool-based zero-allocation — sync.Pool for contexts, byte buffers, HPACK decoders
  • Hardened TLS/mTLS — TLS 1.3 config builder, verified peer state in request contexts, atomic certificate reload
  • ACME / Let's Encrypt — app.ListenAutoTLS(domains, cacheDir) issues and renews certificates automatically via TLS-ALPN-01
  • Prefork & zero-downtime restarts — app.ListenPrefork(addr) runs a multi-process SO_REUSEPORT supervisor; SIGHUP rolls out a new binary with zero dropped connections
  • Outbound HTTP client — connection pooling, retries, circuit breaker, SSRF protection (fh.NewClient)
  • Linux kernel-assisted transport — raw sockets, sharded epoll or io_uring, SO_REUSEPORT CPU steering, socket tuning, and optional XDP admission with safe fallback

Installation

go get github.com/oarkflow/fh

Requires Go 1.26.5 or later.

Quick Start

package main

import (
    "log"

    "github.com/oarkflow/fh"
)

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

    app.Get("/", func(c fh.Ctx) error {
        return c.SendString("Hello, World!")
    })

    log.Fatal(app.ListenWithGracefulShutdown(":8080"))
}

Production application template

Generate a structured server with secure sessions, strict Host/origin policy, RBAC, bounded requests, rate limiting, audit logs, protected health/metrics, SQLite persistence, graceful shutdown, encrypted WASM Fetch with signed ciphertext responses, and a structured, componentized browser frontend ("FH Control Center", built with @oarkflow/lithe):

go run ./cmd/fh-init -module example.com/acme/service -dir ./service
cd service
./run.sh

The generator initializes .env from .env.example and preserves it on subsequent -force regeneration. Add -verify to have it build the server, boot it on a spare loopback port, walk through the app's full HTTP surface (assets, the WASM transport bundle, and the login/secure-bootstrap/logout lifecycle), and open it in your browser - see the generated README's fh-init -verify section. examples/production-app is a checked-in, buildable-in-CI copy of this template's current output.

Loopback development uses short-lived process-local cryptographic keys. The generated server fails closed outside the explicit development environment unless HTTPS and persistent session, login, operations, transport, and response signing secrets are configured. See the generated README and secure WASM transport guide before deployment.

Cross-platform kernel-assisted transport

fh keeps protocol parsing, TLS, routing, middleware, reliability and handlers in memory-safe Go while using the native kernel network facility on each supported server OS:

  • Linux: raw nonblocking sockets with sharded epoll; opt-in probed io_uring; optional SO_REUSEPORT BPF steering and XDP admission.
  • macOS and BSD: raw nonblocking sockets with sharded kqueue accept reactors.
  • Windows: IOCP/overlapped networking through Go's native network poller.
  • Solaris/illumos: event ports through Go's native network poller.
  • AIX: pollset through Go's native network poller.
  • Other server-capable targets: functional native listener backend.

The balanced production profile does not automatically select the newer custom io_uring path. Use the throughput profile or explicitly request io_uring after benchmarking and canary testing it on the deployment kernel.

kernel := fh.ProductionKernelConfig()
kernel.Required = true

app := fh.NewProduction(fh.WithKernel(kernel))
if err := app.ValidateKernelProduction(); err != nil {
    log.Fatal(err)
}
app.Get("/", func(c fh.Ctx) error { return c.SendString("kernel-assisted") })
log.Fatal(app.ListenWithGracefulShutdown(":8080"))

For an aggressive throughput candidate:

kernel := fh.HighPerformanceKernelConfig()
// On Linux this permits probed io_uring auto-selection. Benchmark it against
// ProductionKernelConfig before deployment.

Inspect app.KernelRuntimeInfo() and app.KernelReadiness() at runtime. They report the backend that actually started, fallbacks, connection admission, socket-option failures and deployment warnings. Readiness always requires a workload benchmark because no static configuration is universally fastest.

Probe Linux capabilities without changing the host:

go run ./cmd/fh-kernelctl probe

Optional XDP support is Linux-only and never attached unless explicitly enabled. See kernel-assisted transport and the complete example.

Routing

app.Get("/path", handler)
app.Post("/path", handler)
app.Put("/path", handler)
app.Delete("/path", handler)
app.Patch("/path", handler)
app.Head("/path", handler)
app.Options("/path", handler)
app.All("/path", handler)          // register all methods
app.Add("GET", "/path", handler)   // explicit method string

// Route parameters
app.Get("/users/:id", func(c fh.Ctx) error {
    return c.SendString("User: " + c.Params("id"))
})
app.Get("/files/*path", func(c fh.Ctx) error {
    return c.SendString("File: " + c.Params("path"))
})

// Named routes
app.Get("/users/:id", handler).Name("user.show")
c.RedirectTo("user.show", fh.Map{"id": "42"})

// Route groups
api := app.Group("/api")
api.Get("/users", listUsers)
admin := api.Group("/admin", adminMiddleware)
admin.Get("/dashboard", dashboardHandler)

Typed endpoints (GetTyped, PostTyped, ... AllTyped) provide automatic JSON parsing, validation, struct binding (param/query/header/cookie tags), and OpenAPI schema generation. See Native Features.

See Routing for the full reference.

Middleware

app.Use(logger.New(), recover.New(), cors.New(cors.Config{
    AllowOrigins: []string{"https://example.com"},
}))

// Route- or group-level
app.Get("/dashboard", authMiddleware, dashboardHandler)
admin := app.Group("/admin", authMiddleware, adminLogger)

Commonly used packages:

Package Description
mw/basicauth HTTP Basic Authentication (single-user, multi-user, storage-backed)
mw/apikey API key authentication via header or query
mw/cors Cross-Origin Resource Sharing
mw/csrf CSRF protection
mw/ratelimiter Rate limiting
mw/cache Response caching with TTL
mw/compress / mw/decompress Gzip response compression / bounded request decompression
mw/security Security headers (CSP, HSTS, XFO, etc.)
mw/session Cookie-based sessions with HMAC signing
mw/logger Request logging (common, combined, tiny, json, custom)
mw/recover Panic recovery
mw/requestid / mw/correlationid Request tracking and correlation
mw/realip Trusted proxy-chain parsing, client-IP normalization
mw/timeout / mw/bodylimit Request timeout and body-size limits
mw/circuitbreaker / mw/bulkhead / mw/loadshed Overload and fault protection
mw/proxy Reverse proxy and API gateway handlers
mw/mtls Verified client-certificate authorization
mw/httpsignature Nonce-bound RFC 9421 Ed25519 response signatures
mw/metrics Prometheus-style metrics endpoint

This is a subset — fh ships 70+ middleware packages under mw/, each with its own README.md. See docs/middleware.md for the full reference and recommended ordering, or mw/README.md for the package index.

Body Parsing & Codecs

BodyParser automatically selects the right codec based on Content-Type:

var user User
if err := c.BodyParser(&user); err != nil {
    return err
}
Content-Type Codec
application/json JSON
application/xml, text/xml XML
application/x-www-form-urlencoded Form
multipart/form-data Multipart
text/csv CSV
application/x-ndjson NDJSON
text/plain Plain text
application/octet-stream Binary

Register custom codecs with fh.RegisterCodec(&MyCodec{}). See Codecs.

Responses

c.SendString("text")
c.SendBytes([]byte("data"))
c.SendStream(reader)
c.JSON(data)
c.XML(data)
c.HTML(html)
c.SendFile("path/to/file.pdf")
c.Redirect("/new-path")
c.RedirectTo("route.name", fh.Map{"id": "42"})
c.Status(201).JSON(createdResource)

See Request & Response for the full method reference.

Static Files

import "os"

app.Static("/static", "./public")

app.StaticFS("/", os.DirFS("./public"), fh.StaticConfig{
    Compress:     true,
    Browse:       true,
    IndexFiles:   []string{"index.html", "index.htm"},
    CacheControl: "public, max-age=3600",
})

HTTP/2

fh supports TLS + ALPN (app.ListenTLS(":443", "cert.pem", "key.pem")), h2c prior knowledge, and h2c upgrade from HTTP/1.1. Use fh.WithDisableH2C(true) on cleartext listeners that should accept only HTTP/1; WithSecureByDefault(true) applies that restriction automatically. fh also implements RFC 8441 extended CONNECT, so WebSocket (and other c.Upgrade-based protocols) tunnel over a single HTTP/2 stream instead of requiring an HTTP/1.1 fallback. See HTTP/2.

WebSocket

import "github.com/oarkflow/fh/pkg/websocket"

app.Get("/ws", websocket.New(func(conn *websocket.Conn) error {
    opcode, payload, err := conn.ReadMessage()
    if err != nil {
        return err
    }
    return conn.WriteMessage(opcode, payload)
}))

For pub/sub with rooms, topics, auth, and heartbeats, use pkg/websocket.EventHub:

import "github.com/oarkflow/fh/pkg/websocket"

hub := websocket.NewEventHub(websocket.EventHubConfig{
    Auth: func(client *websocket.EventConn, env websocket.Envelope) error {
        // Revalidate authorization for every non-ack event.
        return nil
    },
})
defer hub.Close()

hub.On("chat.message", func(ctx *websocket.HandlerContext) (any, error) {
    return map[string]any{"accepted": true}, nil
})

wsConfig := websocket.DefaultConfig()
wsConfig.AllowedOrigins = []string{"https://app.example.com"}
app.Get("/ws", hub.Handler(wsConfig, nil))

_ = hub.BroadcastEvent("chat", "general", "chat.message", "Hello everyone!")

See WebSocket.

Error Handling

fh includes a production-safe error framework based on RFC 9457 Problem Details, with typed errors, validation errors, panic recovery, request ID correlation, retryability metadata, and secret redaction.

return fh.NotFound("User not found")
return fh.Unauthorized("Sign in required")
return fh.NewHTTPError(fh.StatusConflict, "USER_EXISTS", "User already exists")

app := fh.NewWithConfig(fh.Config{
    ErrorHandler: func(c fh.Ctx, err error) { _ = c.ErrorResponse(err) },
    NotFoundHandler: func(c fh.Ctx) error {
        return c.Status(fh.StatusNotFound).JSON(fh.Map{"error": "missing"})
    },
})

See Error Framework.

Configuration

app := fh.NewWithConfig(fh.Config{
    ReadTimeout:          10 * time.Second,
    WriteTimeout:         10 * time.Second,
    IdleTimeout:          120 * time.Second,
    RequestBodyTimeout:   10 * time.Second,
    TLSHandshakeTimeout:  10 * time.Second,
    HTTP2IdleTimeout:     60 * time.Second,
    MaxConnections:       10_000,
    MaxRequestBodySize:   4 * 1024 * 1024, // 4MB
    MaxConcurrentStreams: 128,
    ErrorHandler:         customErrorHandler,
    TemplateEngine:       myEngine,
    Debug:                false,
})

See Configuration for the full field reference, and Startup Banner for the ASCII banner shown on Listen.

Sessions

import (
    "time"

    "github.com/oarkflow/fh/mw/session"
    "github.com/oarkflow/fh/pkg/storage/kv"
)

manager := session.NewSessionManager(
    kv.NewMemoryStore(kv.WithGCInterval(time.Hour), kv.WithMaxEntries(100000)),
    session.SessionSecret([]byte("at-least-32-bytes-of-random-secret")),
)
app.Use(session.New(manager))

app.Get("/login", func(c fh.Ctx) error {
    sess := session.Get(c)
    sess.Set("user_id", 42) // the middleware saves the session automatically
    return c.SendString("logged in")
})

Graceful Shutdown

// One-liner with SIGINT/SIGTERM handling
app.ListenWithGracefulShutdown(":8080")

// Manual
go app.Listen(":8080")
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
app.ShutdownWithContext(ctx)

// Context-owned serving for embedded servers and process managers.
// Canceling ctx drains active connections and closes the listener.
ln, _ := net.Listen("tcp", ":8080")
serveCtx, cancel := context.WithCancel(context.Background())
defer cancel()
app.ServeContext(serveCtx, ln)

Prefork & Zero-Downtime Restarts

// Multi-process SO_REUSEPORT supervisor instead of a single process.
// The binary re-executes itself once per worker, so main() (including route
// registration) naturally runs again in every worker.
app.ListenPrefork(":8080")

Send SIGHUP to the master process to roll out a new binary with zero dropped connections: it spawns a fresh generation of workers, waits for them to report a bound listener, then gracefully drains and terminates the previous generation. SIGINT/SIGTERM stops the whole supervisor. On Windows (no SIGHUP), call app.Reload() instead. See Prefork.

ACME / Automatic TLS

// Certificates issued and renewed automatically via TLS-ALPN-01
// (golang.org/x/crypto/acme/autocert — already a dependency, no net/http
// required). CacheDir persists them across restarts.
app.ListenAutoTLS([]string{"example.com"}, "/var/lib/fh/acme-cache")

See ACME.

Reliability Layer

An optional, stdlib-only runtime for request journaling, idempotency, and a durable async job queue — no external queue dependency required.

app := fh.NewWithConfig(fh.Config{
    Reliability: fh.ReliabilityConfig{
        Enabled:            true,
        DataDir:            ".fh-data",
        JournalEnabled:     true,
        IdempotencyEnabled: true,
        QueueEnabled:       true,
        QueueWorkers:       2,
        QueueMaxAttempts:   5,
    },
})
curl -i -X POST http://localhost:3000/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: order-create-001' \
  -d '{"item":"book"}'

Storage is pluggable (pkg/storage/memory, pkg/storage/sql for PostgreSQL/MySQL/SQLite, or implement the interfaces yourself). See Reliability Layer.

Compliance Layer

A built-in Business/Professional/Enterprise/Security compliance layer on top of the router, middleware, reliability, OpenAPI, queue, and security primitives.

app := fh.NewWithConfig(fh.Config{
    Mode: fh.ModeProduction,
    Compliance: fh.ComplianceConfig{
        Enabled:         true,
        Profile:         fh.ComplianceEnterprise,
        Strict:          true,
        ExposeEndpoints: true,
    },
    Audit: fh.AuditConfig{Enabled: true, FilePath: ".fh-data/audit.jsonl", Redact: true},
})

Profiles: business, professional, enterprise, security_strict, financial, healthcare, government, internal_service, public_api, webhook_receiver.

Annotate routes with security metadata so tooling can prove which controls apply:

app.Post("/payments", fh.RequireAuth(), fh.RequireScope("payments:create"), createPayment).
    WithRouteSecurity(fh.RouteSecurityConfig{
        AuthRequired:        true,
        Scopes:              []string{"payments:create"},
        IdempotencyRequired: true,
        AuditRequired:       true,
        DataClass:           "regulated",
    })

When Compliance.ExposeEndpoints is enabled, fh registers /_fh/compliance, /_fh/compliance/controls, /_fh/compliance/findings, /_fh/config/safe, /_fh/runtime, /_fh/routes, /_fh/health, /_fh/live, /_fh/ready, and (when the queue is enabled) /_fh/queue/stats and admin queue ops endpoints.

Outbound HTTP Client

A production-grade HTTP/1.1 + HTTP/2 client lives directly in the root fh package — no separate client/ module.

client := fh.NewClient(fh.ClientConfig{})
resp, err := client.Get(ctx, "https://api.example.com/users")

user, err := fh.GetJSON[User](ctx, client, "https://api.example.com/users/1")

Includes fluent request building, typed helpers (GetJSON[T], PostJSON[Req,Res]), retry policies with jitter backoff, circuit breaker, bulkhead, rate limiting, outbound SSRF protection, and streaming/atomic downloads. See HTTP Client.

Secure WASM Transport

mw/securetransport, the shared pkg/securetransport protocol, and a TypeScript/JavaScript TinyGo/WASM Fetch client under wasm/ provide device-signed session establishment, X25519 key agreement, AES-256-GCM encrypted bodies/headers, replay prevention, and pluggable stores. The secure WASM example additionally negotiates RFC 9421/RFC 9530 Ed25519 signatures over ciphertext and verifies them before decryption.

make wasm

See Secure WASM Transport and examples/secure_wasm.

Signed HTTP Responses

mw/httpsignature and pkg/httpsignature implement a strict RFC 9421 Ed25519 response-signature profile. A fresh client nonce and the originating method and target URI bind each signed response to its request; RFC 9530 Content-Digest binds the exact response bytes.

See RFC 9421 Response Signatures and the runnable Go and WebCrypto clients in examples/rfc9421.

Examples

Full working examples in examples/:

Example Description
basic Minimal "Hello World"
flash-messages Session-backed one-time flash messages and redirects
http-modern Modern HTTP helpers and protocol behavior
kernel_server Kernel-assisted server configuration and readiness
prefork Multi-process prefork serving
secure_wasm Session + secure WASM client demo for encrypted API calls
rfc9421 RFC 9421 signed-response server plus fail-closed Go and WebCrypto clients
production-app Checked-in fh-init output: sessions, RBAC, SQLite, secure WASM transport, and the @oarkflow/lithe frontend

Testing & Benchmarks

go test ./...
go test -bench=. -benchmem ./...

See benchmarks/ for cross-framework comparisons against Fiber and fasthttp, and Performance for hot-path configuration.

Documentation

Full reference documentation is in docs/README.md, covering configuration, routing, codecs, middleware, the reliability layer, HTTP/2, WebSocket, native features (typed endpoints, OpenAPI, SSE), security, and performance.

Known Limitations

fh is a production-oriented, pre-v1 framework. The core HTTP/1.1, HTTP/2 and WebSocket paths have extensive unit, integration, race and fuzz coverage, but a specific deployment is production-ready only after the release gates in docs/production-readiness.md are satisfied. The following product limitations must also be planned around:

  • No HTTP/3 / QUIC. Only HTTP/1.1 and HTTP/2 are implemented. Terminate HTTP/3 at an edge proxy (e.g. a CDN) in front of fh if you need it.
  • No OpenTelemetry (OTLP) export. mw/tracing propagates/parses traceparent headers and mw/metrics exposes a hand-rolled Prometheus text endpoint, but neither ships an OTLP exporter to a collector (Grafana Tempo/Datadog/etc.). Bridge these yourself, or scrape the Prometheus endpoint and configure trace propagation compatible with your existing collector.
  • Process-local defaults. Middleware and cluster state use the shared pkg/storage/kv.Store interface. Defaults are in-process, so rate limits, caches, sessions, replay markers, and cluster leases are per instance unless you configure a shared provider. kv.Provider and fh.WithSharedState give isolated application-wide namespaces and lifecycle management; the built-in providers are memory and single-host files. For a distributed deployment, fh-contrib provides Redis and PostgreSQL kv.Provider adapters with cross-process-atomic Mutate. See Shared State.
  • No gRPC or GraphQL protocol handlers. Only MIME-type constants exist for GraphQL; there's no built-in gRPC server. Both are addressable via a reverse-proxy route (mw/proxy) to a dedicated service if needed.

Security

See SECURITY.md for the supported-version policy and how to report a vulnerability privately. Do not open a public issue for security reports.

License

fh is distributed under the MIT License.

Documentation

Overview

Package fh provides type-safe handler helpers using Go generics. TypedHandler eliminates manual JSON marshaling/unmarshaling and provides compile-time type safety for request/response handling.

Usage:

type CreateUserReq struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

type UserRes struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

app.Post("/users", fh.TypedHandler(func(c fh.Ctx, req CreateUserReq) (UserRes, error) {
    user := UserRes{ID: 1, Name: req.Name}
    return user, nil
}))

Index

Constants

View Source
const (
	HeaderAccept                          = "Accept"
	HeaderAcceptQuery                     = "Accept-Query"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAcceptPost                      = "Accept-Post"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderAge                             = "Age"
	HeaderAllow                           = "Allow"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderAuthorization                   = "Authorization"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderConnection                      = "Connection"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentDigest                   = "Content-Digest"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentRange                    = "Content-Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderContentType                     = "Content-Type"
	HeaderCookie                          = "Cookie"
	HeaderDate                            = "Date"
	HeaderDigest                          = "Digest"
	HeaderDNT                             = "DNT"
	HeaderEarlyData                       = "Early-Data"
	HeaderETag                            = "ETag"
	HeaderExpect                          = "Expect"
	HeaderExpires                         = "Expires"
	HeaderForwarded                       = "Forwarded"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfRange                         = "If-Range"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderLastModified                    = "Last-Modified"
	HeaderLink                            = "Link"
	HeaderLocation                        = "Location"
	HeaderNEL                             = "NEL"
	HeaderOrigin                          = "Origin"
	HeaderPragma                          = "Pragma"
	HeaderPrefer                          = "Prefer"
	HeaderPreferenceApplied               = "Preference-Applied"
	HeaderPriority                        = "Priority"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderRange                           = "Range"
	HeaderReferer                         = "Referer"
	HeaderReprDigest                      = "Repr-Digest"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderRefresh                         = "Refresh"
	HeaderRetryAfter                      = "Retry-After"
	HeaderServer                          = "Server"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderSetCookie2                      = "Set-Cookie2"
	HeaderSourceMap                       = "SourceMap"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderTE                              = "TE"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderUpgrade                         = "Upgrade"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderUserAgent                       = "User-Agent"
	HeaderVary                            = "Vary"
	HeaderVia                             = "Via"
	HeaderWantDigest                      = "Want-Digest"
	HeaderWantContentDigest               = "Want-Content-Digest"
	HeaderWantReprDigest                  = "Want-Repr-Digest"
	HeaderWarning                         = "Warning"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	// Reporting API (https://www.w3.org/TR/reporting/)
	HeaderReportTo           = "Report-To"
	HeaderReportingEndpoints = "Reporting-Endpoints"
)

── Request / response headers ────────────────────────────────────────────────

View Source
const (
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderCrossOriginEmbedderPolicy     = "Cross-Origin-Embedder-Policy"
	HeaderCrossOriginOpenerPolicy       = "Cross-Origin-Opener-Policy"
	HeaderCrossOriginResourcePolicy     = "Cross-Origin-Resource-Policy"
)

── CORS ──────────────────────────────────────────────────────────────────────

View Source
const (
	HeaderSecFetchDest = "Sec-Fetch-Dest"
	HeaderSecFetchMode = "Sec-Fetch-Mode"
	HeaderSecFetchSite = "Sec-Fetch-Site"
	HeaderSecFetchUser = "Sec-Fetch-User"
)

── Fetch metadata ────────────────────────────────────────────────────────────

View Source
const (
	HeaderAcceptCH           = "Accept-CH"
	HeaderCriticalCH         = "Critical-CH"
	HeaderSecCHUA            = "Sec-CH-UA"
	HeaderSecCHUAMobile      = "Sec-CH-UA-Mobile"
	HeaderSecCHUAPlatform    = "Sec-CH-UA-Platform"
	HeaderSecCHUAArch        = "Sec-CH-UA-Arch"
	HeaderSecCHUABitness     = "Sec-CH-UA-Bitness"
	HeaderSecCHUAFullVer     = "Sec-CH-UA-Full-Version"
	HeaderSecCHUAFullVerList = "Sec-CH-UA-Full-Version-List"
	HeaderSecCHUAModel       = "Sec-CH-UA-Model"
	HeaderSaveData           = "Save-Data"
	HeaderViewportWidth      = "Viewport-Width"
	HeaderWidth              = "Width"
	HeaderDPR                = "DPR"
	HeaderDeviceMemory       = "Device-Memory"
	HeaderECT                = "ECT"
	HeaderRTT                = "RTT"
	HeaderDownlink           = "Downlink"
)

── Client hints ──────────────────────────────────────────────────────────────

View Source
const (
	HeaderXForwardedFor    = "X-Forwarded-For"
	HeaderXForwardedHost   = "X-Forwarded-Host"
	HeaderXForwardedPort   = "X-Forwarded-Port"
	HeaderXForwardedProto  = "X-Forwarded-Proto"
	HeaderXForwardedServer = "X-Forwarded-Server"
	HeaderXRealIP          = "X-Real-IP"
	HeaderXRequestID       = "X-Request-ID"
	HeaderXCorrelationID   = "X-Correlation-ID"
	HeaderXRequestStart    = "X-Request-Start"
)

── Proxy / forwarding ────────────────────────────────────────────────────────

View Source
const (
	HeaderPermissionsPolicy             = "Permissions-Policy"
	HeaderFeaturePolicy                 = "Feature-Policy"
	HeaderXContentTypeOptions           = "X-Content-Type-Options"
	HeaderXDNSPrefetchControl           = "X-DNS-Prefetch-Control"
	HeaderXDownloadOptions              = "X-Download-Options"
	HeaderXFrameOptions                 = "X-Frame-Options"
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"
	HeaderXPoweredBy                    = "X-Powered-By"
	HeaderXRequestedWith                = "X-Requested-With"
	HeaderXRobotsTag                    = "X-Robots-Tag"
	HeaderXXSSProtection                = "X-XSS-Protection"
)

── Security / legacy ─────────────────────────────────────────────────────────

View Source
const (
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"
)

── WebSocket ─────────────────────────────────────────────────────────────────

View Source
const (
	HeaderHTTP2Settings = "HTTP2-Settings"
	HeaderAltUsed       = "Alt-Used"
	HeaderConnectionID  = "Connection-ID"
)

── HTTP/2 / HTTP/3 ──────────────────────────────────────────────────────────

View Source
const (
	MIMETextPlain               = "text/plain"
	MIMETextPlainCharsetUTF8    = "text/plain; charset=utf-8"
	MIMETextHTML                = "text/html"
	MIMETextHTMLCharsetUTF8     = "text/html; charset=utf-8"
	MIMETextCSS                 = "text/css"
	MIMETextCSSCharsetUTF8      = "text/css; charset=utf-8"
	MIMETextCSV                 = "text/csv"
	MIMETextCSVCharsetUTF8      = "text/csv; charset=utf-8"
	MIMETextXML                 = "text/xml"
	MIMETextXMLCharsetUTF8      = "text/xml; charset=utf-8"
	MIMETextMarkdown            = "text/markdown"
	MIMETextMarkdownCharsetUTF8 = "text/markdown; charset=utf-8"
	MIMETextEventStream         = "text/event-stream"

	MIMEApplicationJSON            = "application/json"
	MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
	MIMEApplicationXML             = "application/xml"
	MIMEApplicationXMLCharsetUTF8  = "application/xml; charset=utf-8"
	MIMEApplicationForm            = "application/x-www-form-urlencoded"
	MIMEApplicationMultipartForm   = "multipart/form-data"
	MIMEApplicationOctetStream     = "application/octet-stream"
	MIMEApplicationPDF             = "application/pdf"
	MIMEApplicationZip             = "application/zip"
	MIMEApplicationGzip            = "application/gzip"
	MIMEApplicationTar             = "application/x-tar"
	MIMEApplication7z              = "application/x-7z-compressed"
	MIMEApplicationWASM            = "application/wasm"
	MIMEApplicationJavaScript      = "application/javascript"
	MIMEApplicationECMAScript      = "application/ecmascript"
	MIMEApplicationProtobuf        = "application/protobuf"
	MIMEApplicationMsgPack         = "application/msgpack"
	MIMEApplicationNDJSON          = "application/x-ndjson"
	MIMEApplicationGraphQL         = "application/graphql"
	MIMEApplicationGraphQLJSON     = "application/graphql-response+json"
	MIMEApplicationProblemJSON     = "application/problem+json"
	MIMEApplicationProblemXML      = "application/problem+xml"
	MIMEApplicationJWT             = "application/jwt"
	MIMEApplicationCBOR            = "application/cbor"
	MIMEApplicationRSSXML          = "application/rss+xml"
	MIMEApplicationAtomXML         = "application/atom+xml"
	MIMEApplicationSOAPXML         = "application/soap+xml"
	MIMEApplicationYAML            = "application/yaml"
	MIMEApplicationXHTML           = "application/xhtml+xml"

	MIMEImagePNG  = "image/png"
	MIMEImageJPEG = "image/jpeg"
	MIMEImageGIF  = "image/gif"
	MIMEImageWEBP = "image/webp"
	MIMEImageSVG  = "image/svg+xml"
	MIMEImageICO  = "image/x-icon"
	MIMEImageAVIF = "image/avif"
	MIMEImageBMP  = "image/bmp"
	MIMEImageTIFF = "image/tiff"

	MIMEAudioMPEG = "audio/mpeg"
	MIMEAudioMP4  = "audio/mp4"
	MIMEAudioOGG  = "audio/ogg"
	MIMEAudioWAV  = "audio/wav"
	MIMEAudioWEBM = "audio/webm"
	MIMEAudioAAC  = "audio/aac"
	MIMEAudioFLAC = "audio/flac"

	MIMEVideoMP4       = "video/mp4"
	MIMEVideoMPEG      = "video/mpeg"
	MIMEVideoWEBM      = "video/webm"
	MIMEVideoOGG       = "video/ogg"
	MIMEVideoQuickTime = "video/quicktime"
	MIMEVideoAVI       = "video/x-msvideo"

	MIMEFontWOFF  = "font/woff"
	MIMEFontWOFF2 = "font/woff2"
	MIMEFontTTF   = "font/ttf"
	MIMEFontOTF   = "font/otf"
	MIMEFontEOT   = "application/vnd.ms-fontobject"
)

── MIME / content types ──────────────────────────────────────────────────────

View Source
const (
	MethodGET     = "GET"
	MethodHEAD    = "HEAD"
	MethodPOST    = "POST"
	MethodPUT     = "PUT"
	MethodPATCH   = "PATCH"
	MethodDELETE  = "DELETE"
	MethodCONNECT = "CONNECT"
	MethodOPTIONS = "OPTIONS"
	MethodTRACE   = "TRACE"
	MethodQUERY   = "QUERY"

	MethodCOPY       = "COPY"
	MethodLOCK       = "LOCK"
	MethodMKCOL      = "MKCOL"
	MethodMOVE       = "MOVE"
	MethodPROPFIND   = "PROPFIND"
	MethodPROPPATCH  = "PROPPATCH"
	MethodUNLOCK     = "UNLOCK"
	MethodREPORT     = "REPORT"
	MethodMKACTIVITY = "MKACTIVITY"
	MethodCHECKOUT   = "CHECKOUT"
	MethodMERGE      = "MERGE"
	MethodSEARCH     = "SEARCH"
	MethodPURGE      = "PURGE"
)

── HTTP methods ──────────────────────────────────────────────────────────────

View Source
const (
	HTTP09 = "HTTP/0.9"
	HTTP10 = "HTTP/1.0"
	HTTP11 = "HTTP/1.1"
	HTTP2  = "HTTP/2"
	HTTP3  = "HTTP/3"
)

── Protocol versions ─────────────────────────────────────────────────────────

View Source
const (
	CRLF           = "\r\n"
	LF             = "\n"
	CR             = "\r"
	Colon          = ":"
	ColonSpace     = ": "
	Comma          = ","
	CommaSpace     = ", "
	Semicolon      = ";"
	SemicolonSpace = "; "
	Space          = " "
	Tab            = "\t"
	Slash          = "/"
	Question       = "?"
	Ampersand      = "&"
	Equals         = "="
	Dash           = "-"
	Dot            = "."
	Quote          = "\""
)

── Protocol tokens ───────────────────────────────────────────────────────────

View Source
const (
	ValueKeepAlive      = "keep-alive"
	ValueClose          = "close"
	ValueUpgrade        = "upgrade"
	ValueChunked        = "chunked"
	ValueTrailers       = "trailers"
	ValueGzip           = "gzip"
	ValueDeflate        = "deflate"
	ValueBr             = "br"
	ValueZstd           = "zstd"
	ValueCompress       = "compress"
	ValueIdentity       = "identity"
	ValueNoCache        = "no-cache"
	ValueNoStore        = "no-store"
	ValueMaxAge0        = "max-age=0"
	ValuePrivate        = "private"
	ValuePublic         = "public"
	ValueMustRevalidate = "must-revalidate"
	ValueNoTransform    = "no-transform"
	ValueImmutable      = "immutable"
	ValueBytes          = "bytes"
	ValueNone           = "none"
	ValueSameOrigin     = "sameorigin"
	ValueDeny           = "DENY"
	ValueNosniff        = "nosniff"
	ValueWebSocket      = "websocket"
	ValueXMLHttpRequest = "XMLHttpRequest"
	ValueBoundary       = "boundary="
	ValueBearer         = "Bearer"
	ValueBasic          = "Basic"
	ValueDigest         = "Digest"
)

── Header values / connection tokens ─────────────────────────────────────────

View Source
const (
	CharsetUTF8     = "utf-8"
	CharsetUTF16    = "utf-16"
	CharsetISO88591 = "iso-8859-1"
	CharsetUSASCII  = "us-ascii"
)

── Charset names ─────────────────────────────────────────────────────────────

View Source
const (
	CacheNoCache              = "no-cache"
	CacheNoStore              = "no-store"
	CacheNoTransform          = "no-transform"
	CacheOnlyIfCached         = "only-if-cached"
	CacheMaxAge               = "max-age"
	CacheSMaxAge              = "s-maxage"
	CacheMaxStale             = "max-stale"
	CacheMinFresh             = "min-fresh"
	CachePublic               = "public"
	CachePrivate              = "private"
	CacheMustRevalidate       = "must-revalidate"
	CacheProxyRevalidate      = "proxy-revalidate"
	CacheImmutable            = "immutable"
	CacheStaleWhileRevalidate = "stale-while-revalidate"
	CacheStaleIfError         = "stale-if-error"
)

── Cache-Control directives ──────────────────────────────────────────────────

View Source
const (
	CookieSameSiteStrict = "Strict"
	CookieSameSiteLax    = "Lax"
	CookieSameSiteNone   = "None"
)

── SameSite cookie values ────────────────────────────────────────────────────

View Source
const (
	CookieAttrExpires  = "Expires"
	CookieAttrMaxAge   = "Max-Age"
	CookieAttrDomain   = "Domain"
	CookieAttrPath     = "Path"
	CookieAttrSecure   = "Secure"
	CookieAttrHTTPOnly = "HttpOnly"
	CookieAttrSameSite = "SameSite"
	// CookieAttrPartitioned implements CHIPS (Cookies Having Independent
	// Partitioned State) — the cookie is scoped to the top-level site.
	// https://developer.chrome.com/docs/privacy-sandbox/chips/
	CookieAttrPartitioned = "Partitioned"
)

── Cookie attribute names ────────────────────────────────────────────────────

View Source
const (
	HeaderContentTypeStr             = "Content-Type"
	HeaderContentLengthStr           = "Content-Length"
	HeaderConnectionStr              = "Connection"
	HeaderTransferEncodingStr        = "Transfer-Encoding"
	HeaderHostStr                    = "Host"
	HeaderServerStr                  = "Server"
	HeaderDateStr                    = "Date"
	HeaderCacheControlStr            = "Cache-Control"
	HeaderUserAgentStr               = "User-Agent"
	HeaderAuthorizationStr           = "Authorization"
	HeaderAcceptStr                  = "Accept"
	HeaderAcceptEncodingStr          = "Accept-Encoding"
	HeaderAcceptLanguageStr          = "Accept-Language"
	HeaderContentEncodingStr         = "Content-Encoding"
	HeaderContentDispositionStr      = "Content-Disposition"
	HeaderLocationStr                = "Location"
	HeaderSetCookieStr               = "Set-Cookie"
	HeaderCookieStr                  = "Cookie"
	HeaderETagStr                    = "ETag"
	HeaderLastModifiedStr            = "Last-Modified"
	HeaderIfNoneMatchStr             = "If-None-Match"
	HeaderIfModifiedSinceStr         = "If-Modified-Since"
	HeaderIfRangeStr                 = "If-Range"
	HeaderRangeStr                   = "Range"
	HeaderContentRangeStr            = "Content-Range"
	HeaderAcceptRangesStr            = "Accept-Ranges"
	HeaderVaryStr                    = "Vary"
	HeaderAllowStr                   = "Allow"
	HeaderWWWAuthenticateStr         = "WWW-Authenticate"
	HeaderUpgradeStr                 = "Upgrade"
	HeaderOriginStr                  = "Origin"
	HeaderRefererStr                 = "Referer"
	HeaderXRequestedWithStr          = "X-Requested-With"
	HeaderStrictTransportSecurityStr = "Strict-Transport-Security"
	HeaderXContentTypeOptionsStr     = "X-Content-Type-Options"
	HeaderXFrameOptionsStr           = "X-Frame-Options"
	HeaderXXSSProtectionStr          = "X-XSS-Protection"
	HeaderContentSecurityPolicyStr   = "Content-Security-Policy"
	HeaderReferrerPolicyStr          = "Referrer-Policy"
	HeaderPermissionsPolicyStr       = "Permissions-Policy"
	HeaderTrailerStr                 = "Trailer"
	HeaderExpectStr                  = "Expect"
	HeaderHTTP2SettingsStr           = "HTTP2-Settings"

	MethodGETStr     = "GET"
	MethodPOSTStr    = "POST"
	MethodPUTStr     = "PUT"
	MethodDELETEStr  = "DELETE"
	MethodPATCHStr   = "PATCH"
	MethodHEADStr    = "HEAD"
	MethodCONNECTStr = "CONNECT"
	MethodOPTIONSStr = "OPTIONS"
	MethodTRACEStr   = "TRACE"
	MethodQUERYStr   = "QUERY"
)

String variants of header/method constants for user-facing APIs.

View Source
const (
	// MethodQuery is the HTTP QUERY method used by APIs that need a safe, body-capable query operation.
	// Request already uses Query(...) for URL query parameters, so use Request.Do(ctx, MethodQuery, url)
	// or Client.Query(ctx, url, body) for this method.
	MethodQuery     = "QUERY"
	MethodSearch    = "SEARCH"
	MethodPropFind  = "PROPFIND"
	MethodPropPatch = "PROPPATCH"
	MethodMKCol     = "MKCOL"
	MethodCopy      = "COPY"
	MethodMove      = "MOVE"
	MethodLock      = "LOCK"
	MethodUnlock    = "UNLOCK"
	MethodReport    = "REPORT"
	MethodPurge     = "PURGE"
	MethodLink      = "LINK"
	MethodUnlink    = "UNLINK"
)
View Source
const (
	KernelProfileBalanced      = kernel.KernelProfileBalanced
	KernelProfileThroughput    = kernel.KernelProfileThroughput
	KernelProfileLatency       = kernel.KernelProfileLatency
	KernelProfileCompatibility = kernel.KernelProfileCompatibility

	KernelBackendAuto       = kernel.KernelBackendAuto
	KernelBackendStandard   = kernel.KernelBackendStandard
	KernelBackendNative     = kernel.KernelBackendNative
	KernelBackendEpoll      = kernel.KernelBackendEpoll
	KernelBackendIOUring    = kernel.KernelBackendIOUring
	KernelBackendKqueue     = kernel.KernelBackendKqueue
	KernelBackendIOCP       = kernel.KernelBackendIOCP
	KernelBackendEventPorts = kernel.KernelBackendEventPorts
	KernelBackendPollset    = kernel.KernelBackendPollset

	XDPModeNative  = kernel.XDPModeNative
	XDPModeGeneric = kernel.XDPModeGeneric
	XDPModeOffload = kernel.XDPModeOffload

	KernelReadinessInfo    = kernel.ReadinessInfo
	KernelReadinessWarning = kernel.ReadinessWarning
	KernelReadinessError   = kernel.ReadinessError
)
View Source
const (
	HeaderRequestID      = "X-Request-ID"
	HeaderIdempotencyKey = "Idempotency-Key"
	HeaderReplayed       = "X-Idempotency-Replayed"
)
View Source
const (
	PriorityLow    = -10
	PriorityNormal = 0
	PriorityHigh   = 10
)
View Source
const (
	StatusContinue                      = 100
	StatusSwitchingProtocols            = 101
	StatusProcessing                    = 102
	StatusEarlyHints                    = 103
	StatusOK                            = 200
	StatusCreated                       = 201
	StatusAccepted                      = 202
	StatusNonAuthoritativeInformation   = 203
	StatusNoContent                     = 204
	StatusResetContent                  = 205
	StatusPartialContent                = 206
	StatusMultiStatus                   = 207
	StatusAlreadyReported               = 208
	StatusIMUsed                        = 226
	StatusMultipleChoices               = 300
	StatusMovedPermanently              = 301
	StatusFound                         = 302
	StatusSeeOther                      = 303
	StatusNotModified                   = 304
	StatusUseProxy                      = 305
	StatusTemporaryRedirect             = 307
	StatusPermanentRedirect             = 308
	StatusBadRequest                    = 400
	StatusUnauthorized                  = 401
	StatusPaymentRequired               = 402
	StatusForbidden                     = 403
	StatusNotFound                      = 404
	StatusMethodNotAllowed              = 405
	StatusNotAcceptable                 = 406
	StatusProxyAuthenticationRequired   = 407
	StatusRequestTimeout                = 408
	StatusConflict                      = 409
	StatusGone                          = 410
	StatusLengthRequired                = 411
	StatusPreconditionFailed            = 412
	StatusPayloadTooLarge               = 413
	StatusURITooLong                    = 414
	StatusUnsupportedMediaType          = 415
	StatusRangeNotSatisfiable           = 416
	StatusExpectationFailed             = 417
	StatusTeapot                        = 418
	StatusMisdirectedRequest            = 421
	StatusUnprocessableEntity           = 422
	StatusLocked                        = 423
	StatusFailedDependency              = 424
	StatusTooEarly                      = 425
	StatusUpgradeRequired               = 426
	StatusPreconditionRequired          = 428
	StatusTooManyRequests               = 429
	StatusRequestHeaderFieldsTooLarge   = 431
	StatusUnavailableForLegalReasons    = 451
	StatusInternalServerError           = 500
	StatusNotImplemented                = 501
	StatusBadGateway                    = 502
	StatusServiceUnavailable            = 503
	StatusGatewayTimeout                = 504
	StatusHTTPVersionNotSupported       = 505
	StatusVariantAlsoNegotiates         = 506
	StatusInsufficientStorage           = 507
	StatusLoopDetected                  = 508
	StatusNotExtended                   = 510
	StatusNetworkAuthenticationRequired = 511
)

── Status codes ──────────────────────────────────────────────────────────────

View Source
const (
	StatusTextContinue                      = "Continue"
	StatusTextSwitchingProtocols            = "Switching Protocols"
	StatusTextProcessing                    = "Processing"
	StatusTextEarlyHints                    = "Early Hints"
	StatusTextOK                            = "OK"
	StatusTextCreated                       = "Created"
	StatusTextAccepted                      = "Accepted"
	StatusTextNonAuthoritativeInformation   = "Non-Authoritative Information"
	StatusTextNoContent                     = "No Content"
	StatusTextResetContent                  = "Reset Content"
	StatusTextPartialContent                = "Partial Content"
	StatusTextMultiStatus                   = "Multi-Status"
	StatusTextAlreadyReported               = "Already Reported"
	StatusTextIMUsed                        = "IM Used"
	StatusTextMultipleChoices               = "Multiple Choices"
	StatusTextMovedPermanently              = "Moved Permanently"
	StatusTextFound                         = "Found"
	StatusTextSeeOther                      = "See Other"
	StatusTextNotModified                   = "Not Modified"
	StatusTextUseProxy                      = "Use Proxy"
	StatusTextTemporaryRedirect             = "Temporary Redirect"
	StatusTextPermanentRedirect             = "Permanent Redirect"
	StatusTextBadRequest                    = "Bad Request"
	StatusTextUnauthorized                  = "Unauthorized"
	StatusTextPaymentRequired               = "Payment Required"
	StatusTextForbidden                     = "Forbidden"
	StatusTextNotFound                      = "Not Found"
	StatusTextMethodNotAllowed              = "Method Not Allowed"
	StatusTextNotAcceptable                 = "Not Acceptable"
	StatusTextProxyAuthenticationRequired   = "Proxy Authentication Required"
	StatusTextRequestTimeout                = "Request Timeout"
	StatusTextConflict                      = "Conflict"
	StatusTextGone                          = "Gone"
	StatusTextLengthRequired                = "Length Required"
	StatusTextPreconditionFailed            = "Precondition Failed"
	StatusTextPayloadTooLarge               = "Payload Too Large"
	StatusTextURITooLong                    = "URI Too Long"
	StatusTextUnsupportedMediaType          = "Unsupported Media Type"
	StatusTextRangeNotSatisfiable           = "Range Not Satisfiable"
	StatusTextExpectationFailed             = "Expectation Failed"
	StatusTextTeapot                        = "I'm a teapot"
	StatusTextMisdirectedRequest            = "Misdirected Request"
	StatusTextUnprocessableEntity           = "Unprocessable Entity"
	StatusTextLocked                        = "Locked"
	StatusTextFailedDependency              = "Failed Dependency"
	StatusTextTooEarly                      = "Too Early"
	StatusTextUpgradeRequired               = "Upgrade Required"
	StatusTextPreconditionRequired          = "Precondition Required"
	StatusTextTooManyRequests               = "Too Many Requests"
	StatusTextRequestHeaderFieldsTooLarge   = "Request Header Fields Too Large"
	StatusTextUnavailableForLegalReasons    = "Unavailable For Legal Reasons"
	StatusTextInternalServerError           = "Internal Server Error"
	StatusTextNotImplemented                = "Not Implemented"
	StatusTextBadGateway                    = "Bad Gateway"
	StatusTextServiceUnavailable            = "Service Unavailable"
	StatusTextGatewayTimeout                = "Gateway Timeout"
	StatusTextHTTPVersionNotSupported       = "HTTP Version Not Supported"
	StatusTextVariantAlsoNegotiates         = "Variant Also Negotiates"
	StatusTextInsufficientStorage           = "Insufficient Storage"
	StatusTextLoopDetected                  = "Loop Detected"
	StatusTextNotExtended                   = "Not Extended"
	StatusTextNetworkAuthenticationRequired = "Network Authentication Required"
)

── Status reason phrases ─────────────────────────────────────────────────────

Variables

View Source
var (
	ErrInvalidChunkedBody = errors.New("invalid chunked request body")
	ErrBodyTooLarge       = errors.New("request body too large")
)
View Source
var (
	HeaderAcceptBytes                          = []byte(HeaderAccept)
	HeaderAcceptCharsetBytes                   = []byte(HeaderAcceptCharset)
	HeaderAcceptEncodingBytes                  = []byte(HeaderAcceptEncoding)
	HeaderAcceptLanguageBytes                  = []byte(HeaderAcceptLanguage)
	HeaderAcceptPatchBytes                     = []byte(HeaderAcceptPatch)
	HeaderAcceptPostBytes                      = []byte(HeaderAcceptPost)
	HeaderAcceptRangesBytes                    = []byte(HeaderAcceptRanges)
	HeaderAgeBytes                             = []byte(HeaderAge)
	HeaderAllowBytes                           = []byte(HeaderAllow)
	HeaderAltSvcBytes                          = []byte(HeaderAltSvc)
	HeaderAuthorizationBytes                   = []byte(HeaderAuthorization)
	HeaderCacheControlBytes                    = []byte(HeaderCacheControl)
	HeaderClearSiteDataBytes                   = []byte(HeaderClearSiteData)
	HeaderConnectionBytes                      = []byte(HeaderConnection)
	HeaderContentDispositionBytes              = []byte(HeaderContentDisposition)
	HeaderContentEncodingBytes                 = []byte(HeaderContentEncoding)
	HeaderContentLanguageBytes                 = []byte(HeaderContentLanguage)
	HeaderContentLengthBytes                   = []byte(HeaderContentLength)
	HeaderContentLocationBytes                 = []byte(HeaderContentLocation)
	HeaderContentRangeBytes                    = []byte(HeaderContentRange)
	HeaderContentSecurityPolicyBytes           = []byte(HeaderContentSecurityPolicy)
	HeaderContentSecurityPolicyReportOnlyBytes = []byte(HeaderContentSecurityPolicyReportOnly)
	HeaderContentTypeBytes                     = []byte(HeaderContentType)
	HeaderCookieBytes                          = []byte(HeaderCookie)
	HeaderDateBytes                            = []byte(HeaderDate)
	HeaderDigestBytes                          = []byte(HeaderDigest)
	HeaderDNTBytes                             = []byte(HeaderDNT)
	HeaderEarlyDataBytes                       = []byte(HeaderEarlyData)
	HeaderETagBytes                            = []byte(HeaderETag)
	HeaderExpectBytes                          = []byte(HeaderExpect)
	HeaderExpiresBytes                         = []byte(HeaderExpires)
	HeaderForwardedBytes                       = []byte(HeaderForwarded)
	HeaderFromBytes                            = []byte(HeaderFrom)
	HeaderHostBytes                            = []byte(HeaderHost)
	HeaderIfMatchBytes                         = []byte(HeaderIfMatch)
	HeaderIfModifiedSinceBytes                 = []byte(HeaderIfModifiedSince)
	HeaderIfNoneMatchBytes                     = []byte(HeaderIfNoneMatch)
	HeaderIfRangeBytes                         = []byte(HeaderIfRange)
	HeaderIfUnmodifiedSinceBytes               = []byte(HeaderIfUnmodifiedSince)
	HeaderKeepAliveBytes                       = []byte(HeaderKeepAlive)
	HeaderLastEventIDBytes                     = []byte(HeaderLastEventID)
	HeaderLastModifiedBytes                    = []byte(HeaderLastModified)
	HeaderLinkBytes                            = []byte(HeaderLink)
	HeaderLocationBytes                        = []byte(HeaderLocation)
	HeaderNELBytes                             = []byte(HeaderNEL)
	HeaderOriginBytes                          = []byte(HeaderOrigin)
	HeaderPragmaBytes                          = []byte(HeaderPragma)
	HeaderPreferBytes                          = []byte(HeaderPrefer)
	HeaderPriorityBytes                        = []byte(HeaderPriority)
	HeaderProxyAuthenticateBytes               = []byte(HeaderProxyAuthenticate)
	HeaderProxyAuthorizationBytes              = []byte(HeaderProxyAuthorization)
	HeaderRangeBytes                           = []byte(HeaderRange)
	HeaderRefererBytes                         = []byte(HeaderReferer)
	HeaderReferrerPolicyBytes                  = []byte(HeaderReferrerPolicy)
	HeaderRefreshBytes                         = []byte(HeaderRefresh)
	HeaderRetryAfterBytes                      = []byte(HeaderRetryAfter)
	HeaderServerBytes                          = []byte(HeaderServer)
	HeaderServerTimingBytes                    = []byte(HeaderServerTiming)
	HeaderSetCookieBytes                       = []byte(HeaderSetCookie)
	HeaderSetCookie2Bytes                      = []byte(HeaderSetCookie2)
	HeaderSourceMapBytes                       = []byte(HeaderSourceMap)
	HeaderStrictTransportSecurityBytes         = []byte(HeaderStrictTransportSecurity)
	HeaderTEBytes                              = []byte(HeaderTE)
	HeaderTimingAllowOriginBytes               = []byte(HeaderTimingAllowOrigin)
	HeaderTrailerBytes                         = []byte(HeaderTrailer)
	HeaderTransferEncodingBytes                = []byte(HeaderTransferEncoding)
	HeaderUpgradeBytes                         = []byte(HeaderUpgrade)
	HeaderUpgradeInsecureRequestsBytes         = []byte(HeaderUpgradeInsecureRequests)
	HeaderUserAgentBytes                       = []byte(HeaderUserAgent)
	HeaderVaryBytes                            = []byte(HeaderVary)
	HeaderViaBytes                             = []byte(HeaderVia)
	HeaderWantDigestBytes                      = []byte(HeaderWantDigest)
	HeaderWarningBytes                         = []byte(HeaderWarning)
	HeaderWWWAuthenticateBytes                 = []byte(HeaderWWWAuthenticate)

	HeaderAccessControlAllowCredentialsBytes = []byte(HeaderAccessControlAllowCredentials)
	HeaderAccessControlAllowHeadersBytes     = []byte(HeaderAccessControlAllowHeaders)
	HeaderAccessControlAllowMethodsBytes     = []byte(HeaderAccessControlAllowMethods)
	HeaderAccessControlAllowOriginBytes      = []byte(HeaderAccessControlAllowOrigin)
	HeaderAccessControlExposeHeadersBytes    = []byte(HeaderAccessControlExposeHeaders)
	HeaderAccessControlMaxAgeBytes           = []byte(HeaderAccessControlMaxAge)
	HeaderAccessControlRequestHeadersBytes   = []byte(HeaderAccessControlRequestHeaders)
	HeaderAccessControlRequestMethodBytes    = []byte(HeaderAccessControlRequestMethod)
	HeaderCrossOriginEmbedderPolicyBytes     = []byte(HeaderCrossOriginEmbedderPolicy)
	HeaderCrossOriginOpenerPolicyBytes       = []byte(HeaderCrossOriginOpenerPolicy)
	HeaderCrossOriginResourcePolicyBytes     = []byte(HeaderCrossOriginResourcePolicy)

	HeaderSecFetchDestBytes = []byte(HeaderSecFetchDest)
	HeaderSecFetchModeBytes = []byte(HeaderSecFetchMode)
	HeaderSecFetchSiteBytes = []byte(HeaderSecFetchSite)
	HeaderSecFetchUserBytes = []byte(HeaderSecFetchUser)

	HeaderXForwardedForBytes    = []byte(HeaderXForwardedFor)
	HeaderXForwardedHostBytes   = []byte(HeaderXForwardedHost)
	HeaderXForwardedPortBytes   = []byte(HeaderXForwardedPort)
	HeaderXForwardedProtoBytes  = []byte(HeaderXForwardedProto)
	HeaderXForwardedServerBytes = []byte(HeaderXForwardedServer)
	HeaderXRealIPBytes          = []byte(HeaderXRealIP)
	HeaderXRequestIDBytes       = []byte(HeaderXRequestID)
	HeaderXCorrelationIDBytes   = []byte(HeaderXCorrelationID)
	HeaderXRequestStartBytes    = []byte(HeaderXRequestStart)

	HeaderPermissionsPolicyBytes             = []byte(HeaderPermissionsPolicy)
	HeaderFeaturePolicyBytes                 = []byte(HeaderFeaturePolicy)
	HeaderXContentTypeOptionsBytes           = []byte(HeaderXContentTypeOptions)
	HeaderXDNSPrefetchControlBytes           = []byte(HeaderXDNSPrefetchControl)
	HeaderXDownloadOptionsBytes              = []byte(HeaderXDownloadOptions)
	HeaderXFrameOptionsBytes                 = []byte(HeaderXFrameOptions)
	HeaderXPermittedCrossDomainPoliciesBytes = []byte(HeaderXPermittedCrossDomainPolicies)
	HeaderXPoweredByBytes                    = []byte(HeaderXPoweredBy)
	HeaderXRequestedWithBytes                = []byte(HeaderXRequestedWith)
	HeaderXRobotsTagBytes                    = []byte(HeaderXRobotsTag)
	HeaderXXSSProtectionBytes                = []byte(HeaderXXSSProtection)

	HeaderSecWebSocketAcceptBytes     = []byte(HeaderSecWebSocketAccept)
	HeaderSecWebSocketExtensionsBytes = []byte(HeaderSecWebSocketExtensions)
	HeaderSecWebSocketKeyBytes        = []byte(HeaderSecWebSocketKey)
	HeaderSecWebSocketProtocolBytes   = []byte(HeaderSecWebSocketProtocol)
	HeaderSecWebSocketVersionBytes    = []byte(HeaderSecWebSocketVersion)

	HeaderHTTP2SettingsBytes = []byte(HeaderHTTP2Settings)
	HeaderAltUsedBytes       = []byte(HeaderAltUsed)
	HeaderConnectionIDBytes  = []byte(HeaderConnectionID)
)
View Source
var (
	MimeTextPlainBytes               = []byte(MIMETextPlain)
	MimeTextPlainCharsetUTF8Bytes    = []byte(MIMETextPlainCharsetUTF8)
	MimeTextHTMLBytes                = []byte(MIMETextHTML)
	MimeTextHTMLCharsetUTF8Bytes     = []byte(MIMETextHTMLCharsetUTF8)
	MimeTextCSSBytes                 = []byte(MIMETextCSS)
	MimeTextCSSCharsetUTF8Bytes      = []byte(MIMETextCSSCharsetUTF8)
	MimeTextCSVBytes                 = []byte(MIMETextCSV)
	MimeTextCSVCharsetUTF8Bytes      = []byte(MIMETextCSVCharsetUTF8)
	MimeTextXMLBytes                 = []byte(MIMETextXML)
	MimeTextXMLCharsetUTF8Bytes      = []byte(MIMETextXMLCharsetUTF8)
	MimeTextMarkdownBytes            = []byte(MIMETextMarkdown)
	MimeTextMarkdownCharsetUTF8Bytes = []byte(MIMETextMarkdownCharsetUTF8)
	MimeTextEventStreamBytes         = []byte(MIMETextEventStream)

	MimeApplicationJSONBytes            = []byte(MIMEApplicationJSON)
	MimeApplicationJSONCharsetUTF8Bytes = []byte(MIMEApplicationJSONCharsetUTF8)
	MimeApplicationXMLBytes             = []byte(MIMEApplicationXML)
	MimeApplicationXMLCharsetUTF8Bytes  = []byte(MIMEApplicationXMLCharsetUTF8)
	MimeApplicationFormBytes            = []byte(MIMEApplicationForm)
	MimeApplicationMultipartFormBytes   = []byte(MIMEApplicationMultipartForm)
	MimeApplicationOctetStreamBytes     = []byte(MIMEApplicationOctetStream)
	MimeApplicationPDFBytes             = []byte(MIMEApplicationPDF)
	MimeApplicationZipBytes             = []byte(MIMEApplicationZip)
	MimeApplicationGzipBytes            = []byte(MIMEApplicationGzip)
	MimeApplicationTarBytes             = []byte(MIMEApplicationTar)
	MimeApplication7zBytes              = []byte(MIMEApplication7z)
	MimeApplicationWASMBytes            = []byte(MIMEApplicationWASM)
	MimeApplicationJavaScriptBytes      = []byte(MIMEApplicationJavaScript)
	MimeApplicationProtobufBytes        = []byte(MIMEApplicationProtobuf)
	MimeApplicationMsgPackBytes         = []byte(MIMEApplicationMsgPack)
	MimeApplicationNDJSONBytes          = []byte(MIMEApplicationNDJSON)
	MimeApplicationProblemJSONBytes     = []byte(MIMEApplicationProblemJSON)

	MimeImagePNGBytes  = []byte(MIMEImagePNG)
	MimeImageJPEGBytes = []byte(MIMEImageJPEG)
	MimeImageGIFBytes  = []byte(MIMEImageGIF)
	MimeImageWEBPBytes = []byte(MIMEImageWEBP)
	MimeImageSVGBytes  = []byte(MIMEImageSVG)
	MimeImageICOBytes  = []byte(MIMEImageICO)
	MimeImageAVIFBytes = []byte(MIMEImageAVIF)

	MimeAudioMPEGBytes = []byte(MIMEAudioMPEG)
	MimeAudioMP4Bytes  = []byte(MIMEAudioMP4)

	MimeVideoMP4Bytes  = []byte(MIMEVideoMP4)
	MimeVideoMPEGBytes = []byte(MIMEVideoMPEG)

	MimeFontWOFFBytes  = []byte(MIMEFontWOFF)
	MimeFontWOFF2Bytes = []byte(MIMEFontWOFF2)
)
View Source
var (
	MethodGETBytes     = []byte(MethodGET)
	MethodHEADBytes    = []byte(MethodHEAD)
	MethodPOSTBytes    = []byte(MethodPOST)
	MethodPUTBytes     = []byte(MethodPUT)
	MethodPATCHBytes   = []byte(MethodPATCH)
	MethodDELETEBytes  = []byte(MethodDELETE)
	MethodCONNECTBytes = []byte(MethodCONNECT)
	MethodOPTIONSBytes = []byte(MethodOPTIONS)
	MethodTRACEBytes   = []byte(MethodTRACE)
	MethodQUERYBytes   = []byte(MethodQUERY)

	MethodCOPYBytes      = []byte(MethodCOPY)
	MethodLOCKBytes      = []byte(MethodLOCK)
	MethodMKCOLBytes     = []byte(MethodMKCOL)
	MethodMOVEBytes      = []byte(MethodMOVE)
	MethodPROPFINDBytes  = []byte(MethodPROPFIND)
	MethodPROPPATCHBytes = []byte(MethodPROPPATCH)
	MethodUNLOCKBytes    = []byte(MethodUNLOCK)
	MethodPURGEBytes     = []byte(MethodPURGE)
)
View Source
var (
	MethodHTTP09Bytes = []byte(HTTP09)
	MethodHTTP10Bytes = []byte(HTTP10)
	MethodHTTP11Bytes = []byte(HTTP11)
	MethodHTTP2Bytes  = []byte(HTTP2)
	MethodHTTP3Bytes  = []byte(HTTP3)

	CRLFBytes           = []byte(CRLF)
	LFBytes             = []byte(LF)
	CRBytes             = []byte(CR)
	ColonBytes          = []byte(Colon)
	ColonSpaceBytes     = []byte(ColonSpace)
	CommaBytes          = []byte(Comma)
	CommaSpaceBytes     = []byte(CommaSpace)
	SemicolonBytes      = []byte(Semicolon)
	SemicolonSpaceBytes = []byte(SemicolonSpace)
	SpaceBytes          = []byte(Space)
	TabBytes            = []byte(Tab)
	SlashBytes          = []byte(Slash)
	QuestionBytes       = []byte(Question)
	AmpersandBytes      = []byte(Ampersand)
	EqualsBytes         = []byte(Equals)
	DashBytes           = []byte(Dash)
	DotBytes            = []byte(Dot)
	QuoteBytes          = []byte(Quote)
)
View Source
var (
	ValueKeepAliveBytes      = []byte(ValueKeepAlive)
	ValueCloseBytes          = []byte(ValueClose)
	ValueUpgradeBytes        = []byte(ValueUpgrade)
	ValueChunkedBytes        = []byte(ValueChunked)
	ValueTrailersBytes       = []byte(ValueTrailers)
	ValueGzipBytes           = []byte(ValueGzip)
	ValueDeflateBytes        = []byte(ValueDeflate)
	ValueBrBytes             = []byte(ValueBr)
	ValueCompressBytes       = []byte(ValueCompress)
	ValueIdentityBytes       = []byte(ValueIdentity)
	ValueNoCacheBytes        = []byte(ValueNoCache)
	ValueNoStoreBytes        = []byte(ValueNoStore)
	ValueMaxAge0Bytes        = []byte(ValueMaxAge0)
	ValuePrivateBytes        = []byte(ValuePrivate)
	ValuePublicBytes         = []byte(ValuePublic)
	ValueMustRevalidateBytes = []byte(ValueMustRevalidate)
	ValueNoTransformBytes    = []byte(ValueNoTransform)
	ValueImmutableBytes      = []byte(ValueImmutable)
	ValueBytesBytes          = []byte(ValueBytes)
	ValueNoneBytes           = []byte(ValueNone)
	ValueSameOriginBytes     = []byte(ValueSameOrigin)
	ValueDenyBytes           = []byte(ValueDeny)
	ValueNosniffBytes        = []byte(ValueNosniff)
	ValueWebSocketBytes      = []byte(ValueWebSocket)
	ValueXMLHttpRequestBytes = []byte(ValueXMLHttpRequest)
	ValueBoundaryBytes       = []byte(ValueBoundary)
	ValueBearerBytes         = []byte(ValueBearer)
	ValueBasicBytes          = []byte(ValueBasic)
	ValueDigestBytes         = []byte(ValueDigest)
	ValueZstdBytes           = []byte(ValueZstd)
)
View Source
var (
	HeaderReportToBytes           = []byte(HeaderReportTo)
	HeaderReportingEndpointsBytes = []byte(HeaderReportingEndpoints)
)
View Source
var (
	ErrBadRequest           = NewHTTPError(StatusBadRequest, "BAD_REQUEST", "Bad Request")
	ErrUnauthorized         = NewHTTPError(StatusUnauthorized, "UNAUTHORIZED", "Unauthorized")
	ErrForbidden            = NewHTTPError(StatusForbidden, "FORBIDDEN", "Forbidden")
	ErrNotFound             = NewHTTPError(StatusNotFound, "NOT_FOUND", "Not Found")
	ErrMethodNotAllowed     = NewHTTPError(StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method Not Allowed")
	ErrConflict             = NewHTTPError(StatusConflict, "CONFLICT", "Conflict")
	ErrRequestTimeout       = NewHTTPError(StatusRequestTimeout, "REQUEST_TIMEOUT", "Request Timeout")
	ErrPayloadTooLarge      = NewHTTPError(StatusPayloadTooLarge, "PAYLOAD_TOO_LARGE", "Payload Too Large")
	ErrUnsupportedMediaType = NewHTTPError(StatusUnsupportedMediaType, "UNSUPPORTED_MEDIA_TYPE", "Unsupported Media Type")
	ErrTooManyRequests      = NewHTTPError(StatusTooManyRequests, "RATE_LIMITED", "Too Many Requests")
	ErrInternalServerError  = NewHTTPError(StatusInternalServerError, "INTERNAL_ERROR", "Internal Server Error")
	ErrServiceUnavailable   = NewHTTPError(StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "Service Unavailable")
	ErrGatewayTimeout       = NewHTTPError(StatusGatewayTimeout, "GATEWAY_TIMEOUT", "Gateway Timeout")
)

Sentinel error variables for direct comparison. These mirror the Fiber error variables so that migration code like

return fiber.ErrNotFound

compiles as

return fh.ErrNotFound
View Source
var (
	ErrClientRedirectLimit   = errors.New("redirect limit reached")
	ErrClientRedirectBlocked = errors.New("redirect blocked by policy")
	ErrClientBodyTooLarge    = errors.New("body too large")
	ErrClientBodyStreamed    = errors.New("response is streaming")
	ErrClientInvalidURL      = errors.New("invalid url")
	ErrClientHTTPSRequired   = errors.New("https required")
	ErrClientHostBlocked     = errors.New("host blocked by security policy")
	ErrClientCircuitOpen     = errors.New("circuit breaker open")
	ErrClientBulkheadFull    = errors.New("bulkhead capacity exhausted")
	ErrClientStatus          = errors.New("unexpected http status")
)
View Source
var (
	ErrInvalidProxyHeader = errors.New("proxyprotocol: invalid or unsupported proxy header")
	ErrProxyReadTimeout   = errors.New("proxyprotocol: read timeout on header")
	ErrUntrustedPeer      = errors.New("proxyprotocol: PROXY header sent by untrusted peer")
)
View Source
var (
	ErrRouteNotFound     = errors.New("fh: named route not found")
	ErrRouteParamMissing = errors.New("fh: required route parameter missing")
)
View Source
var (
	ErrInvalidUpgrade = errors.New("invalid connection upgrade request")
	ErrHijackHTTP2    = errors.New("connection hijacking is unavailable on HTTP/2 streams")
)
View Source
var DefaultStaticConfig = StaticConfig{
	Index:     "index.html",
	MaxRanges: defaultMaxStaticRanges,
}

DefaultStaticConfig is the default configuration for Static and StaticFS.

View Source
var ErrAppAlreadyStarted = errors.New("fh: app has already been started")
View Source
var ErrDuplicateInboxMessage = errors.New("fh: duplicate inbox message")
View Source
var ErrEnvelopeAADMismatch = errors.New("fh: envelope AAD verification failed")

ErrEnvelopeAADMismatch is returned when AAD verification fails during envelope decryption, indicating the KeyID or Version was tampered with.

View Source
var ErrEnvelopeHashMismatch = errors.New("fh: envelope body hash mismatch")

ErrEnvelopeHashMismatch is returned when the BodyHash in a SecureEnvelope does not match the decrypted plaintext, indicating possible tampering.

View Source
var (
	ErrInvalidBindTarget = errors.New("fh: bind target must be a non-nil pointer")
)
View Source
var ErrInvalidCookie = errors.New("fh: invalid cookie")
View Source
var ErrMalformedRequest = errors.New("malformed HTTP request")

ErrMalformedRequest is returned when the request cannot be parsed.

View Source
var ErrQueueEmpty = errors.New("fh: queue empty")
View Source
var ErrRequestLineTooLarge = errors.New("request line too large")

ErrRequestLineTooLarge is returned when the request line exceeds the limit.

View Source
var ErrRewrite = errors.New("fh: reroute rewritten request")
View Source
var ErrSharedStateUnavailable = errors.New("fh: shared state provider is not configured")

ErrSharedStateUnavailable is returned when an App has no shared-state provider configured.

View Source
var ErrXDPUnsupported = kernel.ErrXDPUnsupported
View Source
var JSONTypeCache sync.Map // map[reflect.Type][]JSONField

Functions

func AppendHeader

func AppendHeader(dst []byte, key, value string) []byte

AppendHeader appends "Key: Value\r\n" to dst — zero alloc with sufficient capacity.

func AppendHeaderBytes

func AppendHeaderBytes(dst []byte, key, value []byte) []byte

AppendHeaderBytes appends "Key: Value\r\n" to dst for byte slices.

func AppendJSONString

func AppendJSONString(dst []byte, s string) []byte

AppendJSONString appends s as a complete quoted JSON string.

func AppendJSONStringContent

func AppendJSONStringContent(dst []byte, s string) []byte

AppendJSONStringContent appends s escaped for JSON string content without surrounding quotes. It is useful with JSONAppend when callers already wrote the opening/closing quote.

func AppendJSONStringContentBytes

func AppendJSONStringContentBytes(dst []byte, b []byte) []byte

AppendJSONStringContentBytes appends b escaped for JSON string content without allocation.

func AtomicHandoff

func AtomicHandoff(c Ctx, jobType string, payload any, opts ...QueueJob) (string, error)

func Bind

func Bind(c Ctx, v any) error

Bind parses request body, query params, and headers into target struct v based on struct tags.

func BindCookie

func BindCookie(c Ctx, v any) error

BindCookie parses cookies into target struct v based on `cookie:"name"` tags.

func BindForm

func BindForm(c Ctx, v any) error

BindForm parses form parameters into target struct v based on `form:"key"` tags.

func BindHeader

func BindHeader(c Ctx, v any) error

BindHeader parses request headers into target struct v based on `header:"Header-Name"` tags.

func BindJSON

func BindJSON(c Ctx, v any) error

BindJSON unmarshals request body into target struct v.

func BindParams

func BindParams(c Ctx, v any) error

BindParams parses named route parameters into target struct v based on `params:"name"` tags.

func BindQuery

func BindQuery(c Ctx, v any) error

BindQuery parses URL query string parameters into target struct v based on `query:"key"` tags.

func BuildXDP

func BuildXDP(source, output string) error

func Bytes

func Bytes(s string) []byte

Bytes returns a mutable []byte copy of s.

func BytesEqualFold

func BytesEqualFold(a, b []byte) bool

func ClientSecurityDialContext

func ClientSecurityDialContext(sec ClientSecurity, base *net.Dialer) func(context.Context, string, string) (net.Conn, error)

ClientSecurityDialContext returns a DialContext wrapper enforcing the security policy after DNS resolution and before connect. It resolves DNS once, validates the resolved IPs, and connects directly to the resolved IP to prevent TOCTOU races where DNS could change between validation and connect.

func ClientTraceParent

func ClientTraceParent(ctx context.Context, traceparent string) context.Context

func ConstantTimeEqual

func ConstantTimeEqual(a, b string) bool

Security helpers.

func DecodeBody

func DecodeBody(data []byte, contentType string, v any) error

DecodeBody decodes data using the registered codec for contentType.

func DecodeForm

func DecodeForm(data []byte, v any) error

DecodeForm parses application/x-www-form-urlencoded or query-string data.

func DecodeHeaders

func DecodeHeaders(h *RequestHeader, v any) error

DecodeHeaders populates v from the parsed request headers.

Supported target types:

  • *map[string]string — first value per header, canonical key
  • *map[string][]string — all values per header, canonical key
  • struct pointer — each exported field is matched by the header name specified in its `header:"name"` tag (case-insensitive). When the tag is absent the lower-cased field name is used. Supported field kinds: string, []string, int, int64, uint64, float64, bool, *string.

func DefaultXDPPinPath

func DefaultXDPPinPath(name string) string

func DeleteResponseHeader

func DeleteResponseHeader(c Ctx, name string) bool

DeleteResponseHeader removes a response header when the concrete context supports mutation. It keeps the public Ctx interface stable for adapters.

func DetachXDP

func DetachXDP(iface string, mode XDPMode) error

func DeterministicIdempotencyKey

func DeterministicIdempotencyKey(parts ...string) string

DeterministicIdempotencyKey creates a stable key from deterministic parts.

func EmitSecurityEvent

func EmitSecurityEvent(c Ctx, typ string, data map[string]any)

func EncodeBody

func EncodeBody(contentType string, v any) ([]byte, error)

EncodeBody encodes v using a registered encoder codec.

func GetJSON

func GetJSON[T any](ctx context.Context, c *Client, u string) (T, error)

Generic typed helpers.

func HasHeaderToken

func HasHeaderToken(value []byte, token string) bool

func InboxDedupeKey

func InboxDedupeKey(source string, payload []byte) string

func JSONMarshal

func JSONMarshal(v any) ([]byte, error)

JSONMarshal is a convenience wrapper over the active JSON engine with the same direct-path behavior as jsonCodec.Marshal.

func JSONTypeSupported

func JSONTypeSupported(t reflect.Type, seen map[reflect.Type]bool) bool

func JSONUnmarshal

func JSONUnmarshal(data []byte, v any) error

JSONUnmarshal is a convenience wrapper over the active JSON engine with the same UseNumber/default strict single-document behavior as jsonCodec.Unmarshal.

func MaskCard

func MaskCard(v string) string

func MaskEmail

func MaskEmail(v string) string

func MustSetJSONEngine

func MustSetJSONEngine(engine JSONEngine)

MustSetJSONEngine is the panic-on-error variant for process startup.

func Negotiate

func Negotiate(ctx Ctx, offered []string) string

Negotiate returns the best content type from the client's Accept header.

func NewACMEManager

func NewACMEManager(opt ACMEOptions) (*autocert.Manager, error)

NewACMEManager builds an autocert.Manager from opt. The returned Manager's TLSConfig method is the intended way to obtain a *tls.Config for ServeTLS/ListenTLS; use ListenAutoTLS for the common case.

func NewServerTLSConfig

func NewServerTLSConfig(opt ServerTLSOptions) (*tls.Config, error)

NewServerTLSConfig returns a validated, server-side TLS configuration.

func OpenEnvelope

func OpenEnvelope(policy DataPolicy, env SecureEnvelope) ([]byte, error)

func ParseCookie

func ParseCookie(header string) map[string]string

ParseCookie parses a Cookie request header value into a name-value map.

func PostJSON

func PostJSON[Req any, Res any](ctx context.Context, c *Client, u string, body Req) (Res, error)

func ProblemDetails

func ProblemDetails(c Ctx, status int, title, detail, typeURI string) error

ProblemDetails sends an RFC 9457 / RFC 7807 application/problem+json error response.

func PutJSON

func PutJSON[Req any, Res any](ctx context.Context, c *Client, u string, body Req) (Res, error)

func RedactSecret

func RedactSecret(s string) string

func RedactSecrets

func RedactSecrets(s string) string

RedactSecrets removes common secret-bearing values from debug strings.

func RedactValue

func RedactValue(key string, value any) any

func RegisterCodec

func RegisterCodec(c Codec)

RegisterCodec registers or replaces a codec. It panics only for programmer errors. Use RegisterCodecStrict when you prefer an error return.

func RegisterCodecAlias

func RegisterCodecAlias(contentType string, c Codec)

RegisterCodecAlias registers another content type for an existing codec.

func RegisterCodecStrict

func RegisterCodecStrict(c Codec) error

RegisterCodecStrict registers or replaces a codec.

func RegisterRule

func RegisterRule(name string, fn ruleFunc)

RegisterRule registers a custom validation rule. It is safe for concurrent use.

func RenderStartupBanner

func RenderStartupBanner(cfg StartupBannerConfig, data StartupBannerData) string

RenderStartupBanner returns the default pretty ASCII startup banner. It is exported so tests and CLIs can render/preview the banner without starting a listener.

func ReplaceRequestBody

func ReplaceRequestBody(c Ctx, body []byte) bool

ReplaceRequestBody installs a middleware-produced request body for the remainder of the current request. It is intended for bounded decompression, decryption, and normalization middleware.

func RequestTLSState

func RequestTLSState(c Ctx) (tls.ConnectionState, bool)

RequestTLSState returns the TLS state for c. Plaintext requests return false.

func ResetJSONEngine

func ResetJSONEngine()

ResetJSONEngine restores the compatibility backend.

func SSEvent

func SSEvent(c Ctx, event string, data any) error

SSEvent sends a standalone Server-Sent Event (SSE) to the client with proper headers.

func SetClientIP

func SetClientIP(c Ctx, value string) bool

SetClientIP replaces the request's effective client address after a trusted proxy middleware has validated the forwarding chain. It returns false for an invalid address or a custom Ctx implementation that does not support an override.

func SetCodecOptions

func SetCodecOptions(opt CodecOptions)

SetCodecOptions updates defensive codec limits. Zero values keep current/default values.

func SetJSONEngine

func SetJSONEngine(engine JSONEngine) error

SetJSONEngine swaps the JSON backend used by application/json, text/json, application/problem+json, application/ld+json, and +json suffix matching. Call it once during startup before serving requests.

func SetPrincipal

func SetPrincipal(c Ctx, p Principal)

func SignCookie

func SignCookie(value string, secret []byte) string

func StatusReason

func StatusReason(code int) string

StatusReason returns the standard reason phrase for code. It returns an empty string for unknown status codes.

func StrEqFold

func StrEqFold(b []byte, s string) bool

func StreamJSON

func StreamJSON(ctx Ctx, fn func(json.Encoder) error) error

StreamJSON streams a JSON response without buffering the entire body. Useful for large datasets or real-time data.

func StreamNDJSON

func StreamNDJSON(ctx Ctx, fn func(yield func(any) bool)) error

StreamNDJSON streams newline-delimited JSON (NDJSON) for real-time data.

func TLSStateFromContext

func TLSStateFromContext(ctx context.Context) (tls.ConnectionState, bool)

TLSStateFromContext returns the TLS connection-state snapshot attached to a context. It is available for both HTTP/1.1 and HTTP/2 requests accepted by a TLS listener.

func TenantID

func TenantID(c Ctx) string

func TrimOWS

func TrimOWS(b []byte) []byte

func ValidToken

func ValidToken(b []byte) bool

func ValidateStruct

func ValidateStruct(s any) error

ValidateStruct validates a struct using its "validate" struct tags. It returns a *ValidationError with field-level details, or nil if valid.

func ValidateStructWith

func ValidateStructWith(s any) error

ValidateStructWith runs validation and calls a custom Validator if implemented.

func VerifyChain

func VerifyChain(checkpoints []MerkleCheckpoint) error

VerifyChain verifies that a chain of checkpoints is valid by checking PrevCheckpointHash links and event count continuity.

func VerifyCheckpoint

func VerifyCheckpoint(cp MerkleCheckpoint, eventHashes []string) bool

VerifyCheckpoint verifies that a checkpoint's Merkle root matches the given event hashes.

func VerifySignedCookie

func VerifySignedCookie(s string, secret []byte) (string, bool)

func WithBudget

func WithBudget(ctx context.Context, b *Budget) context.Context

WithBudget stores the budget in the request context.

func WithTLSState

func WithTLSState(ctx context.Context, state tls.ConnectionState) context.Context

WithTLSState attaches an immutable TLS connection-state snapshot to a request context. Servers normally do this automatically; the exported helper is useful for adapters and tests that construct contexts themselves.

func WriteAll

func WriteAll(w io.Writer, b []byte) error

Types

type ACMEOptions

type ACMEOptions struct {
	// Domains is the exact set of hostnames this server is authorized to
	// request certificates for. Required.
	Domains []string
	// CacheDir persists issued certificates and account state to disk across
	// restarts. Required — without it, every restart re-issues certificates
	// and risks hitting the CA's rate limits.
	CacheDir string
	// Email is an optional contact address the CA may use to warn about
	// certificate problems.
	Email string
	// HostPolicy overrides the default autocert.HostWhitelist(Domains...)
	// policy, e.g. to allow subdomains dynamically.
	HostPolicy autocert.HostPolicy
}

ACMEOptions configures automatic certificate issuance and renewal via an ACME CA (Let's Encrypt by default, through golang.org/x/crypto/acme/autocert — already a dependency of this module for OCSP stapling in tls_config.go).

fh has no net/http dependency, so it deliberately supports only the tls-alpn-01 challenge type (RFC 8737): it needs no second listener, no port-80 HTTP handler, and no acme.ALPNProto plumbing beyond what Manager.TLSConfig already does. Environments that terminate TLS in front of fh cannot complete tls-alpn-01 and are out of scope — use a manually provisioned certificate with CertificateReloader instead in that case.

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Field   string `json:"field,omitempty"`
}

APIError represents a typed API error.

type App

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

App is the top-level application object. Create with New().

func New

func New(opts ...Option) *App

New creates a new App with functional options. Call with zero options to use defaults. Example:

app := fh.New(
    fh.WithReadTimeout(5*time.Second),
    fh.WithWriteTimeout(10*time.Second),
    fh.WithDebug(true),
)

New defaults to Config.Mode = ModeProduction, which only tightens protocol and connection-handling behavior (see NewProduction). It does not enable authentication, CSRF protection, rate limiting, or a Host allow-list, and it does not imply SecureByDefault — see WithSecureByDefault for what that separate, still application-scoped, opt-in adds.

func NewEnterprise

func NewEnterprise(opts ...Option) *App

NewEnterprise creates an app with strict protocol validation, audit, reliability, redaction and compliance evidence endpoints enabled.

The compliance/health/runtime endpoints this mounts (/_fh/compliance, /_fh/routes, /_fh/runtime, /_fh/config/safe, ...) expose security posture details including the full route table annotated with which routes lack auth. Pass fh.WithComplianceEndpointAuth(yourAuthMiddleware) as one of opts so these routes aren't reachable unauthenticated; omitting it logs a startup warning and surfaces a critical finding from ValidateSecurity.

func NewFast

func NewFast(opts ...Option) *App

NewFast creates an app with benchmark-oriented defaults. Use this only behind a trusted edge or for controlled latency/RPS benchmarks. To avoid request-hot activity atomics, shutdown closes HTTP/1 connections immediately; use NewProduction when graceful completion of in-flight requests is required.

WriteTimeout defaults to 0 here (unlike New/NewProduction's 30s): a non-zero WriteTimeout makes serveConn set a socket write deadline AND derive a fresh per-request context.Context via context.WithTimeout on every request, which costs real allocation, mutex, and GC overhead in the hot path. Pass WithWriteTimeout after NewFast's options to restore write deadlines and handler-visible cancellation if this app is exposed beyond a trusted edge.

func NewProduction

func NewProduction(opts ...Option) *App

NewProduction creates an app with production-safe protocol defaults while keeping the request hot path allocation-sensitive.

"Production-safe protocol defaults" means exactly Config.Mode = ModeProduction: tighter protocol validation and the connection/timeout bounds ValidateSecurity checks for. Despite the name, NewProduction does NOT by itself add authentication, authorization, CSRF protection, rate limiting, or a Host allow-list (Config.AllowedHosts) — every one of those remains the application's responsibility to mount explicitly (mw/basicauth, mw/apikey, mw/session, mw/csrf, mw/ratelimiter, WithAllowedHosts, ...). Layering WithSecureByDefault(true) on top additionally hardens response headers and bounds every untrusted protocol dimension (buffer sizes, connection/body limits) — it still does not touch auth/CSRF/rate-limiting. Call app.ValidateSecurity() (or GET /_fh/compliance/findings if compliance endpoints are mounted) to see what's actually configured for a given app, and see docs/production-readiness.md for the full release-gate checklist.

func NewWithConfig

func NewWithConfig(cfg Config) *App

NewWithConfig creates a new App from a Config struct. Non-zero fields override defaults; nil handlers are replaced with built-in defaults. This is a convenience for users who prefer a single config object.

app := fh.NewWithConfig(fh.Config{
    ReadTimeout: 5 * time.Second,
    WriteTimeout: 10 * time.Second,
})

func (*App) Add

func (a *App) Add(method, path string, handlers ...HandlerFunc) *App

func (*App) AddHealthCheck

func (a *App) AddHealthCheck(name string, timeout time.Duration, fn func(context.Context) error) *App

AddHealthCheck adds a named health check function with a timeout to App.

func (*App) All

func (a *App) All(path string, handlers ...HandlerFunc) *App

func (*App) AllTyped

func (a *App) AllTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) ComplianceControls

func (a *App) ComplianceControls() []ComplianceControl

func (*App) ComplianceReport

func (a *App) ComplianceReport() ComplianceReport

func (*App) Connect

func (a *App) Connect(path string, handlers ...HandlerFunc) *App

func (*App) ConnectTyped

func (a *App) ConnectTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) Delete

func (a *App) Delete(path string, handlers ...HandlerFunc) *App

func (*App) DeleteTyped

func (a *App) DeleteTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) EnableComplianceEndpoints

func (a *App) EnableComplianceEndpoints(prefix string, middleware ...HandlerFunc) *App

EnableComplianceEndpoints mounts compliance/config introspection routes. These expose security posture details (which routes require auth, redaction /audit status, config limits) — pass an auth middleware (e.g. mw/basicauth, mw/apikey, IP allowlist) so this route group isn't reachable by anyone who can reach the server.

func (*App) EnableDocs

func (a *App) EnableDocs(path string) *App

func (*App) EnableHealth

func (a *App) EnableHealth(prefix string, middleware ...HandlerFunc) *App

EnableHealth mounts liveness/readiness routes. /ready surfaces raw health-check error strings (which can include DSNs or internal hostnames), so in deployments reachable from outside a trusted network, pass an auth middleware.

func (*App) EnableOpenAPI

func (a *App) EnableOpenAPI(path string, cfg OpenAPIConfig) *App

func (*App) EnableRouteList

func (a *App) EnableRouteList(path string, middleware ...HandlerFunc) *App

EnableRouteList mounts a route-table introspection endpoint. It reveals every route's path, method, and security metadata (including which routes have no auth requirement) — pass an auth middleware in deployments reachable from outside a trusted network.

func (*App) EnableRuntime

func (a *App) EnableRuntime(prefix string, middleware ...HandlerFunc) *App

EnableRuntime mounts runtime/route-table/queue-stats introspection routes. /routes exposes the full route table annotated with which routes require auth — a reconnaissance map for an attacker — so pass an auth middleware in any deployment reachable from outside a trusted network.

func (*App) EnableSecurityEvents

func (a *App) EnableSecurityEvents(path string) *SecurityEventStream

func (*App) EnableSwaggerUI

func (a *App) EnableSwaggerUI(prefix string) *App

EnableSwaggerUI mounts an embedded interactive Swagger UI documentation viewer at prefix and live OpenAPI spec at prefix/openapi.json.

func (*App) ErrorCount

func (a *App) ErrorCount(code string) uint64

ErrorCount returns the number of errors rendered for a stable error code.

func (*App) Get

func (a *App) Get(path string, handlers ...HandlerFunc) *App

func (*App) GetTyped

func (a *App) GetTyped(path string, handler any, middleware ...HandlerFunc) *App

PostTyped registers a typed JSON endpoint. Go does not support generic methods, so the handler is supplied as a typed function with this shape:

func(fh.Ctx, CreateUserRequest) (UserResponse, error)

fh validates that shape at registration time and builds the parsing/encoding wrapper.

func (*App) Group

func (a *App) Group(prefix string, handlers ...HandlerFunc) *Group

Group creates a route group with a shared prefix and optional middleware.

func (*App) Head

func (a *App) Head(path string, handlers ...HandlerFunc) *App

func (*App) HeadTyped

func (a *App) HeadTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) HealthCheck

func (a *App) HealthCheck(path string, config HealthConfig) *App

HealthCheck registers a health check endpoint at path with configured probes.

func (*App) HealthStatus

func (a *App) HealthStatus(ctx context.Context) (bool, []HealthCheckResult)

HealthStatus runs all registered health checks and returns overall readiness and individual results.

func (*App) Inbox

func (a *App) Inbox() *Inbox

func (*App) IsDraining

func (a *App) IsDraining() bool

func (*App) KernelReadiness

func (a *App) KernelReadiness() KernelReadinessReport

func (*App) KernelRuntimeInfo

func (a *App) KernelRuntimeInfo() KernelRuntimeInfo

func (*App) Listen

func (a *App) Listen(addr string) error

func (*App) ListenAutoTLS

func (a *App) ListenAutoTLS(domains []string, cacheDir string) error

ListenAutoTLS serves HTTPS on :443 with certificates issued and renewed automatically via ACME tls-alpn-01. It is the ACME counterpart to ListenTLS.

func (*App) ListenAutoTLSWithGracefulShutdown

func (a *App) ListenAutoTLSWithGracefulShutdown(domains []string, cacheDir string) error

ListenAutoTLSWithGracefulShutdown is the graceful-shutdown counterpart to ListenAutoTLS, draining on SIGINT/SIGTERM exactly like ListenTLSWithGracefulShutdown.

func (*App) ListenContext

func (a *App) ListenContext(ctx context.Context, addr string) error

ListenContext binds addr and serves until ctx is canceled. Cancellation initiates graceful shutdown and waits for the serving loop to exit.

func (*App) ListenPrefork

func (a *App) ListenPrefork(addr string, opts ...PreforkOption) error

ListenPrefork serves addr using a supervisor of Workers OS processes bound to the same port via SO_REUSEPORT, instead of a single process. The calling binary re-executes itself for each worker, so route registration in main() naturally runs again in every worker — call it exactly where you would otherwise call Listen or ListenWithGracefulShutdown.

The same mechanism doubles as a zero-downtime restart facility: sending SIGHUP to the master process (Unix; use Reload on Windows) spawns a fresh generation of workers, waits for them to report a bound listener, then gracefully drains and terminates the previous generation — the listening port stays accepting connections throughout. SIGINT/SIGTERM to the master gracefully stops the whole supervisor.

func (*App) ListenProxyProtocol

func (a *App) ListenProxyProtocol(addr string, cfg ...ProxyProtocolConfig) error

ListenProxyProtocol starts listening on addr with PROXY protocol v1/v2 support.

func (*App) ListenTLS

func (a *App) ListenTLS(addr, certFile, keyFile string) error

ListenTLS serves HTTPS using the standard library TLS stack.

func (*App) ListenTLSContext

func (a *App) ListenTLSContext(ctx context.Context, addr, certFile, keyFile string) error

ListenTLSContext is the context-aware TLS counterpart to ListenContext.

func (*App) ListenTLSProxyProtocol

func (a *App) ListenTLSProxyProtocol(addr, certFile, keyFile string, cfg ...ProxyProtocolConfig) error

ListenTLSProxyProtocol starts listening on addr with TLS and PROXY protocol v1/v2 support.

func (*App) ListenTLSWithGracefulShutdown

func (a *App) ListenTLSWithGracefulShutdown(addr, certFile, keyFile string) error

ListenTLSWithGracefulShutdown is the TLS counterpart to ListenWithGracefulShutdown. It loads the certificate pair, negotiates HTTP/2 through ALPN when enabled, and drains on SIGINT or SIGTERM.

func (*App) ListenUnix

func (a *App) ListenUnix(path string) error

ListenUnix serves HTTP over a Unix-domain socket. The socket path is removed when serving stops. Existing paths are never overwritten; net.Listen returns an error if the requested path is already occupied.

func (*App) ListenUnixContext

func (a *App) ListenUnixContext(ctx context.Context, path string) error

ListenUnixContext is the context-aware Unix-domain socket counterpart to ListenContext.

func (*App) ListenWithGracefulShutdown

func (a *App) ListenWithGracefulShutdown(addr string) error

ListenWithGracefulShutdown starts the server and blocks until SIGINT or SIGTERM is received, then performs a graceful shutdown. If ShutdownTimeout is configured, the server will force-close remaining connections after that duration. Use OnShutdown to register cleanup hooks.

func (*App) Logger

func (a *App) Logger() Logger

Logger returns the application logger so middleware and integrations can emit structured messages without reaching into App internals.

func (*App) Meta

func (a *App) Meta(key string, val any) *App

Meta attaches key-value metadata to the most recently registered route.

func (*App) Metrics

func (a *App) Metrics() ServerMetrics

Metrics returns a real-time snapshot of server runtime metrics.

func (*App) Mount

func (a *App) Mount(prefix string, sub *App) *App

Mount mounts a sub-App onto a path prefix, registering all sub-routes, handlers, tags, and metadata.

func (*App) MustStateStore

func (a *App) MustStateStore(namespace string) kv.Store

MustStateStore is the initialization-oriented form of StateStore. It panics when shared state is unavailable or the namespace cannot be opened.

func (*App) Name

func (a *App) Name(name string) *App

Name names the most recently registered route, allowing fluent usage such as app.Get("/users/:id", handler).Name("users.show").

func (*App) OnClose

func (a *App) OnClose(fn func(net.Conn)) *App

func (*App) OnConnect

func (a *App) OnConnect(fn func(net.Conn)) *App

func (*App) OnError

func (a *App) OnError(fn func(error)) *App

func (*App) OnListen

func (a *App) OnListen(fn HookFunc) *App

func (*App) OnRoute

func (a *App) OnRoute(fn func(RouteInfo)) *App

func (*App) OnShutdown

func (a *App) OnShutdown(fn HookFunc) *App

func (*App) OpenAPI

func (a *App) OpenAPI() map[string]any

func (*App) OpenAPISpec

func (a *App) OpenAPISpec() map[string]any

OpenAPISpec generates an OpenAPI 3.0 specification map from all registered routes.

func (*App) Options

func (a *App) Options(path string, handlers ...HandlerFunc) *App

func (*App) OptionsTyped

func (a *App) OptionsTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) Outbox

func (a *App) Outbox() *Outbox

func (*App) Patch

func (a *App) Patch(path string, handlers ...HandlerFunc) *App

func (*App) PatchTyped

func (a *App) PatchTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) Post

func (a *App) Post(path string, handlers ...HandlerFunc) *App

func (*App) PostTyped

func (a *App) PostTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) Purge

func (a *App) Purge(path string, handlers ...HandlerFunc) *App

Purge registers a PURGE method route (common in CDN/cache invalidation APIs).

func (*App) Put

func (a *App) Put(path string, handlers ...HandlerFunc) *App

func (*App) PutTyped

func (a *App) PutTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) Query

func (a *App) Query(path string, handlers ...HandlerFunc) *App

func (*App) QueryTyped

func (a *App) QueryTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) Queue

func (a *App) Queue() *DurableQueue

Queue returns the embedded durable queue when reliability queue support is enabled.

func (*App) REF added in v0.0.26

func (a *App) REF() REFEngine

REF returns the REF Engine, or nil if REF is not enabled.

func (*App) Reliability

func (a *App) Reliability() *Reliability

Reliability returns the configured reliability runtime, if enabled.

func (*App) Reload

func (a *App) Reload() error

Reload triggers a rolling restart of an active ListenPrefork master's worker generation, identical to what sending SIGHUP does on Unix. It is the documented way to trigger a zero-downtime restart on platforms without SIGHUP (Windows), and is available on every platform for programmatic use (e.g. from an external control endpoint). It returns an error if this process is not currently running as a ListenPrefork master.

func (*App) Report

func (a *App) Report(path string, handlers ...HandlerFunc) *App

Report registers a REPORT method route (WebDAV, CalDAV/CardDAV report queries).

func (*App) RouteTreeString

func (a *App) RouteTreeString() string

RouteTreeString returns an ASCII list representation of registered routes.

func (*App) Routes

func (a *App) Routes() []RouteInfo

func (*App) RuntimeInfo

func (a *App) RuntimeInfo() RuntimeInfo

func (*App) SafeConfig

func (a *App) SafeConfig() SafeConfig

func (*App) Search

func (a *App) Search(path string, handlers ...HandlerFunc) *App

Search registers a SEARCH method route (RFC 5323, WebDAV, CalDAV searches).

func (*App) Serve

func (a *App) Serve(ln net.Listener) error

func (*App) ServeContext

func (a *App) ServeContext(ctx context.Context, ln net.Listener) error

ServeContext serves ln until it is closed, the application shuts down, or ctx is canceled. Cancellation initiates the same graceful shutdown path as ShutdownWithContext, making it suitable for signal-aware process managers and embedded servers. The context is not used as a per-request deadline.

func (*App) ServeTLS

func (a *App) ServeTLS(ln net.Listener, config *tls.Config) error

ServeTLS wraps ln with TLS and advertises HTTP/2 through ALPN when enabled.

func (*App) SetREF added in v0.0.26

func (a *App) SetREF(engine REFEngine) *App

SetREF sets the Runtime Execution Fabric (REF) engine on the App.

func (*App) Shutdown

func (a *App) Shutdown() error

func (*App) ShutdownWithContext

func (a *App) ShutdownWithContext(ctx context.Context) error

func (*App) ShutdownWithTimeout

func (a *App) ShutdownWithTimeout(d time.Duration) error

func (*App) StateStore

func (a *App) StateStore(ctx context.Context, namespace string) (kv.Store, error)

StateStore resolves an isolated feature namespace from the configured shared-state provider. The provider owns the returned store; do not close an individual namespace store.

func (*App) Static

func (a *App) Static(prefix, root string, config ...StaticConfig) *App

Static registers a GET route that serves files from root on disk.

func (*App) StaticFS

func (a *App) StaticFS(prefix string, filesystem fs.FS, config ...StaticConfig) *App

StaticFS registers a GET route that serves files from an fs.FS (embed.FS, etc.).

func (*App) Tag

func (a *App) Tag(tags ...string) *App

Tag attaches tags to the most recently registered route.

func (*App) Test

func (a *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error)

Test executes a standard *http.Request directly against app in-memory over net.Pipe() without binding TCP ports.

func (*App) Trace

func (a *App) Trace(path string, handlers ...HandlerFunc) *App

func (*App) TraceTyped

func (a *App) TraceTyped(path string, handler any, middleware ...HandlerFunc) *App

func (*App) URL

func (a *App) URL(name string, params ...map[string]string) (string, error)

URL generates a URL path for a named route.

func (*App) URLWithQuery

func (a *App) URLWithQuery(name string, params map[string]any, query map[string]any) (string, error)

URLWithQuery builds a URL path for a named route and appends URL-encoded query parameters.

func (*App) Use

func (a *App) Use(handlers ...HandlerFunc) *App

Use registers global middleware (applied to all routes).

func (*App) ValidateKernelProduction

func (a *App) ValidateKernelProduction() error

func (*App) ValidateSecurity

func (a *App) ValidateSecurity() []SecurityFinding

func (*App) WithDataPolicy

func (a *App) WithDataPolicy(p DataPolicy) *App

func (*App) WithRouteSecurity

func (a *App) WithRouteSecurity(cfg RouteSecurityConfig) *App

WithRouteSecurity annotates the latest route with compliance metadata.

func (*App) WriteAudit

func (a *App) WriteAudit(ctx context.Context, e AuditEvent) error

type AtomicJobOptions

type AtomicJobOptions struct {
	Type           string
	Body           []byte
	Priority       int
	Delay          time.Duration
	RunAt          time.Time
	ConcurrencyKey string
	Headers        map[string]string
	MaxAttempts    int
}

type AtomicJobResult

type AtomicJobResult struct {
	ID string `json:"id"`
}

func AtomicJob

func AtomicJob(c Ctx, opt AtomicJobOptions) (*AtomicJobResult, error)

type AuditConfig

type AuditConfig struct {
	Enabled   bool          `json:"enabled"`
	FilePath  string        `json:"file_path,omitempty"`
	Sink      AuditSink     `json:"-"`
	Redact    bool          `json:"redact"`
	Retention time.Duration `json:"retention,omitempty"`
}

AuditConfig controls compliance-grade business/security audit logging.

type AuditEvent

type AuditEvent struct {
	ID             string         `json:"id"`
	Time           time.Time      `json:"time"`
	RequestID      string         `json:"request_id,omitempty"`
	CorrelationID  string         `json:"correlation_id,omitempty"`
	TenantID       string         `json:"tenant_id,omitempty"`
	ActorID        string         `json:"actor_id,omitempty"`
	ActorType      string         `json:"actor_type,omitempty"`
	Action         string         `json:"action"`
	Resource       string         `json:"resource,omitempty"`
	ResourceID     string         `json:"resource_id,omitempty"`
	Result         string         `json:"result,omitempty"`
	Reason         string         `json:"reason,omitempty"`
	Method         string         `json:"method,omitempty"`
	Path           string         `json:"path,omitempty"`
	IP             string         `json:"ip,omitempty"`
	DataClass      string         `json:"data_class,omitempty"`
	DataCategories []string       `json:"data_categories,omitempty"`
	Metadata       map[string]any `json:"metadata,omitempty"`
}

type AuditRecorder

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

func (AuditRecorder) Record

func (r AuditRecorder) Record(action, resource, resourceID string, meta ...map[string]any) error

type AuditSink

type AuditSink interface {
	WriteAudit(context.Context, AuditEvent) error
}

type AuditSinkCloser

type AuditSinkCloser interface {
	AuditSink
	Close() error
}

type BatchResult

type BatchResult struct {
	Response *Response
	Error    error
	Index    int
}

type Budget

type Budget struct {
	// Deadline is the absolute time by which the request must complete.
	Deadline time.Time

	// MaxCPUTime is the maximum CPU time allowed for this request.
	MaxCPUTime time.Duration

	// MaxQueueTime is the maximum time the request may spend waiting in queues.
	MaxQueueTime time.Duration

	// MaxBodyBytes is the maximum allowed request body size in bytes.
	MaxBodyBytes int64

	// MaxResponseBytes is the maximum allowed response body size in bytes.
	MaxResponseBytes int64

	// MaxMemoryBytes is the maximum memory this request may allocate.
	MaxMemoryBytes int64

	// MaxUpstreamCalls limits the number of outbound HTTP calls.
	MaxUpstreamCalls int

	// MaxRetries limits the number of automatic retries.
	MaxRetries int

	// MaxLogBytes limits the total bytes written to logs for this request.
	MaxLogBytes int64
	// contains filtered or unexported fields
}

Budget holds per-request execution limits. A budget travels with the request through middleware, handlers, database calls, and HTTP clients, ensuring no single request can consume unbounded resources.

func BudgetFromContext

func BudgetFromContext(ctx context.Context) *Budget

BudgetFromContext extracts the budget from a request context.

func NewBudget

func NewBudget(cfg BudgetConfig) *Budget

NewBudget creates a budget from a config and starts its deadline.

func (*Budget) CanRetry

func (b *Budget) CanRetry(current int) bool

CanRetry reports whether the budget allows another retry.

func (*Budget) CanUpstream

func (b *Budget) CanUpstream() bool

CanUpstream reports whether the budget allows another upstream call.

func (*Budget) CheckBodySize

func (b *Budget) CheckBodySize(size int64) bool

CheckBodySize reports whether the body size fits the budget.

func (*Budget) CheckMemory

func (b *Budget) CheckMemory(bytes int64) bool

CheckMemory reports whether the requested allocation fits the budget.

func (*Budget) Child

func (b *Budget) Child(d time.Duration, split BudgetSplit) *Budget

Child carves a sub-budget from the parent. The child inherits the parent's deadline but may have a shorter one. Memory, retries, and upstream call budgets are split proportionally.

Example:

parent := BudgetFromContext(c.Context())
dbBudget := parent.Child(700*time.Millisecond, BudgetSplit{
    MemoryFraction: 0.3,
    UpstreamFraction: 0.5,
    RetryFraction: 1.0,
})

func (*Budget) Expired

func (b *Budget) Expired() bool

Expired reports whether the budget has exceeded its deadline.

func (*Budget) Remaining

func (b *Budget) Remaining() time.Duration

Remaining returns the time remaining until the budget deadline. If no deadline is set, it returns the maximum duration.

func (*Budget) String

func (b *Budget) String() string

String returns a human-readable summary of the budget.

func (*Budget) WithDeadline

func (b *Budget) WithDeadline(d time.Duration) *Budget

WithDeadline returns a child budget with a shorter deadline.

type BudgetConfig

type BudgetConfig struct {
	Deadline         time.Duration
	MaxCPUTime       time.Duration
	MaxQueueTime     time.Duration
	MaxBodyBytes     int64
	MaxResponseBytes int64
	MaxMemoryBytes   int64
	MaxUpstreamCalls int
	MaxRetries       int
	MaxLogBytes      int64
}

BudgetConfig holds budget defaults for a route or application.

type BudgetSplit

type BudgetSplit struct {
	// MemoryFraction is the fraction of parent memory budget (0.0-1.0).
	MemoryFraction float64

	// UpstreamFraction is the fraction of parent upstream call budget (0.0-1.0).
	UpstreamFraction float64

	// RetryFraction is the fraction of parent retry budget (0.0-1.0).
	RetryFraction float64

	// LogFraction is the fraction of parent log budget (0.0-1.0).
	LogFraction float64
}

BudgetSplit defines how a parent budget is divided among children.

type ByteRange

type ByteRange struct {
	Start int64
	End   int64
}

ByteRange represents a single parsed segment from a Range request header. Both Start and End are byte offsets, inclusive. Start=0, End=N-1 for the entire resource of size N.

type CertPinningConfig

type CertPinningConfig struct {
	// Pins maps hostname -> list of acceptable SHA-256 SPKI hashes (base64 encoded).
	Pins      map[string][]string
	BackupPin string
}

CertPinningConfig configures certificate pinning for outbound TLS connections.

func (*CertPinningConfig) Verifier

func (pc *CertPinningConfig) Verifier() func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error

Verifier returns a function suitable for tls.Config.VerifyPeerCertificate that enforces certificate pinning. Unpinned hosts fail-closed (rejected).

type CertificateReloader

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

CertificateReloader atomically swaps a PEM certificate/key pair.

func NewCertificateReloader

func NewCertificateReloader(certFile, keyFile string) (*CertificateReloader, error)

func (*CertificateReloader) GetCertificate

func (r *CertificateReloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)

func (*CertificateReloader) Reload

func (r *CertificateReloader) Reload() error

type CircuitBreaker

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

func NewCircuitBreaker

func NewCircuitBreaker(cfg CircuitConfig) *CircuitBreaker

func (*CircuitBreaker) Middleware

func (b *CircuitBreaker) Middleware() ClientMiddleware

type CircuitConfig

type CircuitConfig struct {
	FailureThreshold uint64
	RecoveryTimeout  time.Duration
	HalfOpenMax      uint64
}

Circuit breaker middleware.

type Client

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

Client is a high-performance, middleware-first outbound HTTP client for fh.

func NewClient

func NewClient(cfg ...ClientConfig) *Client

NewClient creates a production-ready HTTP client. Middleware can be added via Use.

func (*Client) Async

func (c *Client) Async(fn func(*Request) (*Response, error)) *FutureResponse

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, maxConcurrency int, fns ...func(*Request) (*Response, error)) []BatchResult

func (*Client) Close

func (c *Client) Close() error

Close releases idle connections and runs lifecycle hooks.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, u string) (*Response, error)

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, u string) (*Response, error)

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, u string, body ...any) (*Response, error)

func (*Client) Get

func (c *Client) Get(ctx context.Context, u string) (*Response, error)

func (*Client) Head

func (c *Client) Head(ctx context.Context, u string) (*Response, error)

func (*Client) Options

func (c *Client) Options(ctx context.Context, u string) (*Response, error)

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, u string, body any) (*Response, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, u string, body any) (*Response, error)

func (*Client) Put

func (c *Client) Put(ctx context.Context, u string, body any) (*Response, error)

func (*Client) Query

func (c *Client) Query(ctx context.Context, u string, body any) (*Response, error)

func (*Client) R

func (c *Client) R() *Request

R returns a reusable fluent request builder. Do not use the returned Request concurrently.

func (*Client) Search

func (c *Client) Search(ctx context.Context, u string, body any) (*Response, error)

func (*Client) Service

func (c *Client) Service(base string) *ServiceClient

func (*Client) Trace

func (c *Client) Trace(ctx context.Context, u string) (*Response, error)

func (*Client) Use

func (c *Client) Use(m ...ClientMiddleware) *Client

Use appends outbound middlewares. It is intended to be called during startup.

type ClientConfig

type ClientConfig struct {
	BaseURL               string
	UserAgent             string
	Timeout               time.Duration
	DialTimeout           time.Duration
	KeepAlive             time.Duration
	TLSHandshakeTimeout   time.Duration
	ResponseHeaderTimeout time.Duration
	ExpectContinueTimeout time.Duration
	IdleConnTimeout       time.Duration
	MaxIdleConns          int
	MaxIdleConnsPerHost   int
	MaxConnsPerHost       int
	DisableCompression    bool
	DisableKeepAlives     bool
	ForceAttemptHTTP2     bool
	TLSConfig             *tls.Config
	// AllowInsecureTLS must be explicitly enabled before a TLSConfig with
	// InsecureSkipVerify can be used. Prefer normal certificate validation;
	// certificate pinning also requires a verified chain.
	AllowInsecureTLS  bool
	Proxy             func(*http.Request) (*url.URL, error)
	Jar               http.CookieJar
	Transport         http.RoundTripper
	Logger            Logger
	Metrics           ClientMetrics
	Hooks             ClientHooks
	Security          ClientSecurity
	Retry             RetryPolicy
	Redirect          RedirectPolicy
	BodyLimit         int64
	ResponseBodyLimit int64
}

ClientConfig configures the fh outbound HTTP client. The zero value is safe, but NewClient applies production-grade connection pooling and timeout defaults.

type ClientError

type ClientError struct {
	Kind        ClientErrorKind
	Method, URL string
	StatusCode  int
	Duration    time.Duration
	Attempt     int
	Retryable   bool
	Err         error
}

func (*ClientError) Error

func (e *ClientError) Error() string

func (*ClientError) Unwrap

func (e *ClientError) Unwrap() error

type ClientErrorKind

type ClientErrorKind string

Errors.

const (
	ClientErrNetwork  ClientErrorKind = "network"
	ClientErrTimeout  ClientErrorKind = "timeout"
	ClientErrTLS      ClientErrorKind = "tls"
	ClientErrRedirect ClientErrorKind = "redirect"
	ClientErrSecurity ClientErrorKind = "security"
	ClientErrProtocol ClientErrorKind = "protocol"
	ClientErrPanic    ClientErrorKind = "panic"
	ClientErrStatus   ClientErrorKind = "status"
)

type ClientEvent

type ClientEvent struct {
	At                time.Time
	Method, URL, Host string
	StatusCode        int
	Attempt           int
	Duration          time.Duration
	Err               error
}

type ClientHooks

type ClientHooks struct{ OnClientStart, OnClientClose, OnBeforeRequest, OnRequestSent, OnResponseHeaders, OnAfterResponse, OnRetry, OnRedirect, OnError, OnDNSStart, OnDNSDone, OnConnectStart, OnConnectDone, OnTLSHandshakeStart, OnTLSHandshakeDone, OnConnectionOpen, OnConnectionReuse func(ClientEvent) }

ClientHooks exposes modern lifecycle extension points.

type ClientMetrics

type ClientMetrics interface {
	Inflight(delta int64)
	Observe(method, host string, status int, dur time.Duration)
	Error(method, host, kind string)
}

ClientMetrics is intentionally small and allocation-free for adapters.

type ClientMiddleware

type ClientMiddleware func(http.RoundTripper) http.RoundTripper

ClientMiddleware wraps outbound HTTP round trips.

func ClientAPIKey

func ClientAPIKey(header, key string) ClientMiddleware

func ClientBasicAuth

func ClientBasicAuth(user, pass string) ClientMiddleware

func ClientBearer

func ClientBearer(token string) ClientMiddleware

func ClientBearerTokenSource

func ClientBearerTokenSource(src TokenSource) ClientMiddleware

ClientBearerTokenSource adds Authorization: Bearer <token> using a pluggable token source.

func ClientBodyLimit

func ClientBodyLimit(n int64) ClientMiddleware

func ClientBulkhead

func ClientBulkhead(max int, wait time.Duration) ClientMiddleware

func ClientCache

func ClientCache(cache *MemoryHTTPCache) ClientMiddleware

func ClientCircuitBreaker

func ClientCircuitBreaker(cfg CircuitConfig) ClientMiddleware

func ClientGzipRequest

func ClientGzipRequest(min int) ClientMiddleware

func ClientHMACSigner

func ClientHMACSigner(header, secret string) ClientMiddleware

func ClientHeader

func ClientHeader(k, v string) ClientMiddleware

func ClientIdempotency

func ClientIdempotency(provider func(*http.Request) string) ClientMiddleware

func ClientLoadBalance

func ClientLoadBalance(sel EndpointSelector) ClientMiddleware

func ClientLogger

func ClientLogger(l Logger) ClientMiddleware

Built-in middlewares.

func ClientRateLimit

func ClientRateLimit(ratePerSecond int) ClientMiddleware

func ClientRecover

func ClientRecover() ClientMiddleware

func ClientRequestID

func ClientRequestID(header string) ClientMiddleware

ClientRequestID propagates an existing request id or creates a compact random id.

func ClientRequireStatus

func ClientRequireStatus(allow func(int) bool) ClientMiddleware

ClientRequireStatus converts unexpected HTTP status codes into structured ClientError.

func ClientTraceContext

func ClientTraceContext() ClientMiddleware

type ClientSecurity

type ClientSecurity struct {
	Strict          bool
	AllowPrivateIPs bool
	AllowLocalhost  bool
	AllowedHosts    map[string]bool
	BlockedHosts    map[string]bool
	RequireHTTPS    bool
}

ClientSecurity protects outbound calls against SSRF and unsafe redirects.

func (ClientSecurity) Enabled

func (s ClientSecurity) Enabled() bool

func (ClientSecurity) Validate

func (s ClientSecurity) Validate(u *url.URL) error

type ClientStatsMetrics

type ClientStatsMetrics struct {
	InFlight atomic.Int64
	Requests atomic.Uint64
	Errors   atomic.Uint64
	BytesIn  atomic.Uint64
}

ClientStatsMetrics is an in-memory low-overhead metrics collector.

func (*ClientStatsMetrics) Error

func (m *ClientStatsMetrics) Error(string, string, string)

func (*ClientStatsMetrics) Inflight

func (m *ClientStatsMetrics) Inflight(d int64)

func (*ClientStatsMetrics) Observe

type Codec

type Codec interface {
	// ContentType returns the canonical MIME type handled by this codec,
	// for example application/json.
	ContentType() string

	// Unmarshal decodes data into v.
	Unmarshal(data []byte, v any) error
}

Codec unmarshals request bodies for a content type.

This interface intentionally stays tiny for hot-path dispatch. Codecs can optionally implement ContentTypeAwareCodec, EncoderCodec, or ResettableCodec.

type CodecOptions

type CodecOptions struct {
	MaxFormPairs          int
	MaxFormKeyBytes       int
	MaxFormValueBytes     int
	MaxFormDepth          int
	MaxMultipartParts     int
	MaxMultipartFieldSize int64
	MaxMultipartFileSize  int64
	MaxNDJSONLineBytes    int
	MaxCSVRecordBytes     int
}

CodecOptions controls defensive limits. These limits are intentionally sane defaults and can be changed at process startup with SetCodecOptions.

type ComplianceConfig

type ComplianceConfig struct {
	Enabled         bool              `json:"enabled"`
	Profile         ComplianceProfile `json:"profile,omitempty"`
	Strict          bool              `json:"strict,omitempty"`
	ExposeEndpoints bool              `json:"expose_endpoints,omitempty"`
	EndpointPrefix  string            `json:"endpoint_prefix,omitempty"`

	// EndpointAuth guards the compliance/health/runtime introspection routes
	// mounted by ExposeEndpoints. These routes expose the full route table
	// (including which routes lack auth), config internals, and queue
	// depth — a reconnaissance goldmine if left unauthenticated. Set this
	// (e.g. to an mw/basicauth, mw/apikey, or IP-allowlist handler) before
	// enabling ExposeEndpoints in any deployment reachable from outside a
	// trusted network. Left empty, ValidateSecurity reports a critical
	// finding and a startup warning is logged.
	EndpointAuth []HandlerFunc `json:"-"`

	// FailOnCritical panics at app construction when ValidateSecurity finds a
	// critical production issue. This is useful in CI and strict deployments.
	FailOnCritical bool `json:"fail_on_critical,omitempty"`

	// SecurityContact is the contact email/address for the security.txt endpoint.
	SecurityContact string `json:"security_contact,omitempty"`
	// SecurityPolicyURL is the URL of the security policy for security.txt.
	SecurityPolicyURL string `json:"security_policy_url,omitempty"`
}

ComplianceConfig configures compliance-first runtime behavior.

type ComplianceControl

type ComplianceControl struct {
	ID          string   `json:"id"`
	Standard    string   `json:"standard"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Implemented bool     `json:"implemented"`
	Components  []string `json:"components,omitempty"`
	Evidence    []string `json:"evidence,omitempty"`
}

ComplianceControl maps an fh runtime capability to an external control family.

type ComplianceProfile

type ComplianceProfile string

ComplianceProfile selects a built-in security/compliance baseline. fh does not certify an application; profiles enable controls and expose evidence that maps to common enterprise/security review requirements.

const (
	ComplianceBusiness       ComplianceProfile = "business"
	ComplianceProfessional   ComplianceProfile = "professional"
	ComplianceEnterprise     ComplianceProfile = "enterprise"
	ComplianceSecurityStrict ComplianceProfile = "security_strict"
	ComplianceFinancial      ComplianceProfile = "financial"
	ComplianceHealthcare     ComplianceProfile = "healthcare"
	ComplianceGovernment     ComplianceProfile = "government"
	ComplianceInternal       ComplianceProfile = "internal_service"
	CompliancePublicAPI      ComplianceProfile = "public_api"
	ComplianceWebhook        ComplianceProfile = "webhook_receiver"
)

type ComplianceReport

type ComplianceReport struct {
	GeneratedAt time.Time           `json:"generated_at"`
	Mode        Mode                `json:"mode"`
	Profile     ComplianceProfile   `json:"profile"`
	Controls    []ComplianceControl `json:"controls"`
	Findings    []SecurityFinding   `json:"findings"`
	Routes      []RouteInfo         `json:"routes"`
	Config      SafeConfig          `json:"config"`
}

ComplianceReport is the complete runtime compliance evidence document.

type Config

type Config struct {
	// Kernel enables Linux epoll/io_uring accept reactors, SO_REUSEPORT CPU steering,
	// socket tuning and optional XDP packet admission. Portable serving remains the fallback.
	Kernel KernelConfig
	// SecureByDefault enables the framework's fail-closed protocol and response
	// baseline. It is resolved once while the app is built, so disabled servers
	// pay no request-path cost. Application-specific authentication,
	// authorization, CORS, CSRF, rate-limit, and Host allow-list (AllowedHosts)
	// policies must still be installed explicitly because the framework cannot
	// infer them safely. This is true of every mode, including
	// ModeProduction/NewProduction — "production mode" and "secure by default"
	// are two separate, narrower-than-they-sound opt-ins. See
	// docs/production-readiness.md.
	SecureByDefault bool
	// Mode controls secure default and compliance validation behavior.
	Mode Mode
	// Compliance enables business/professional/enterprise/security evidence endpoints and profiles.
	Compliance ComplianceConfig
	// Audit configures compliance-grade business/security audit records.
	Audit AuditConfig
	// Redaction controls sensitive field masking across audit, logs, journals and examples.
	Redaction   RedactionConfig
	ReadTimeout time.Duration
	// ReadHeaderTimeout bounds request-line and header reads independently from
	// the body budget. It starts when the first request byte arrives, preventing
	// slowloris clients from extending a deadline one byte at a time.
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	// HandlerTimeout bounds handler execution through Ctx.Context. It is
	// independent from WriteTimeout so long-lived streaming responses can refresh
	// socket write deadlines without inheriting an arbitrary handler lifetime.
	// Zero means no framework-level handler deadline.
	HandlerTimeout time.Duration
	// RequestBodyTimeout is an absolute budget for receiving one request body.
	RequestBodyTimeout time.Duration
	// StreamRequestBody defers request-body buffering and enables
	// Ctx.StreamBody for upload endpoints. Unconsumed bodies are drained before
	// keep-alive reuse; Body and BodyParser still materialize the body on demand.
	StreamRequestBody bool
	// TLSHandshakeTimeout bounds the server-side TLS handshake.
	TLSHandshakeTimeout time.Duration
	// HTTP2IdleTimeout bounds the interval between HTTP/2 frames.
	HTTP2IdleTimeout time.Duration
	MaxConnections   int
	// MaxConnectionsPerIP limits simultaneously open TCP connections from one
	// socket peer. It is enforced before TLS handshakes and HTTP parsing. Zero
	// disables the per-peer limit; SecureByDefault caps it at 100.
	MaxConnectionsPerIP int
	// MaxInFlightRequests caps requests concurrently executing in handlers across
	// the whole server. Zero disables the check. SecureByDefault sets a bound so
	// a burst of slow/expensive requests cannot exhaust goroutines/memory before
	// application-level rate limiting is installed.
	MaxInFlightRequests int64
	// MaxGoroutines rejects new requests once runtime.NumGoroutine() (sampled at
	// ResourceCheckInterval) exceeds this bound. Zero disables the check.
	// SecureByDefault sets a bound as defense-in-depth against slowloris-style
	// goroutine exhaustion beyond what connection/timeout limits catch.
	MaxGoroutines int
	// MaxHeapBytes rejects new requests once sampled heap allocation exceeds this
	// bound. Zero disables the check. SecureByDefault sets a bound.
	MaxHeapBytes uint64
	// ResourceCheckInterval controls how often goroutine/heap stats are resampled
	// for MaxGoroutines/MaxHeapBytes. Defaults to 250ms.
	ResourceCheckInterval time.Duration
	// DisablePanicRecovery removes the application-level panic recovery defer from
	// every request. It is useful for trusted benchmark/edge deployments that use
	// process supervision or explicit recover middleware. Leave false for robust
	// production defaults.
	DisablePanicRecovery bool
	// SafeParams forces route params to be copied into stable strings. Leave false
	// for high-throughput handlers; turn on only when params are stored after the request.
	SafeParams bool
	// CaptureResponseBody keeps a copy of every response for middleware/tests.
	// It is disabled by default; reliability/cache middleware opt in per request.
	CaptureResponseBody bool
	// SendDateHeader emits an RFC 9110 Date header on HTTP/1.1 responses. It is
	// disabled by default because modern high-throughput frameworks omit it on
	// benchmark hot paths and the Date line costs bytes plus append work on every
	// response. Enable it at your edge/origin boundary when required by policy.
	SendDateHeader bool
	// SendKeepAliveHeader emits an explicit Connection: keep-alive header for
	// HTTP/1.1 keep-alive responses. It is disabled by default because keep-alive
	// is implicit in HTTP/1.1; Connection: close is still emitted when needed.
	SendKeepAliveHeader bool
	// ServerHeader, when non-empty, is sent as the Server response header.
	// Empty by default (no Server header sent) for security.
	ServerHeader string
	// AllowedHosts restricts Host/:authority values accepted by the server.
	// An empty list preserves the historical behavior and accepts any host.
	AllowedHosts []string
	// ContentSecurityPolicy adds a CSP response header when hardening is active.
	// Keep it empty for APIs; set it for browser-facing HTML endpoints.
	ContentSecurityPolicy string
	ReadBufferSize        int
	// WriteBufferSize is the initial size of the per-connection write buffer.
	// Defaults to ReadBufferSize when zero. Increase for streaming-heavy workloads.
	WriteBufferSize      int
	MaxRequestBodySize   int
	MaxHeaderListSize    int
	MaxHeaderCount       int
	MaxRequestLineSize   int
	MaxConcurrentStreams uint32
	DisableKeepAlive     bool
	DisableHTTP2         bool
	// DisableH2C rejects cleartext HTTP/2 prior knowledge and HTTP/1.1 h2c
	// upgrades while retaining HTTP/2 over TLS/ALPN.
	DisableH2C bool
	// HSTSPreload enables the HSTS preload directive when SecureByDefault is active.
	// Submit the domain to hstspreload.org after enabling.
	HSTSPreload      bool
	ErrorHandler     ErrorHandler
	NotFoundHandler  NotFoundHandler
	MethodNotAllowed MethodNotAllowedHandler
	OptionsHandler   OptionsHandler
	// RequestHeadHandler runs after request-line/header validation and route
	// matching but before 100-continue and body reads. Return nil without writing
	// a response to accept the body; return an error or write a response to reject
	// it early. The handler must not attempt to read Body.
	RequestHeadHandler HandlerFunc
	// ConnContext derives the base context for each accepted connection. The
	// returned context is inherited by every request on that connection and is
	// canceled when the connection closes. A nil return uses context.Background.
	ConnContext func(context.Context, net.Conn) context.Context
	// BaseContext supplies the parent context for a serving listener. It is
	// called once when serving starts; a nil return uses context.Background.
	BaseContext    func(net.Listener) context.Context
	Logger         Logger
	TemplateEngine TemplateEngine
	// SharedState supplies isolated, interface-based state stores to sessions,
	// rate limits, replay protection, caches, cluster coordination and other
	// features. The App owns the provider and closes it during graceful
	// shutdown after user shutdown hooks have completed.
	SharedState SharedStateProvider
	// Reliability enables request journal, idempotency, and durable async queue.
	Reliability ReliabilityConfig
	// Environment controls safe error exposure defaults. Use EnvDevelopment locally and EnvProduction in production.
	Environment Environment
	// ErrorOptions controls RFC 9457 problem details, redaction, and debug extensions.
	ErrorOptions ErrorOptions
	// Debug exposes private error causes in 500 responses. Keep disabled in production.
	Debug bool
	// ShutdownTimeout is the maximum duration to wait for active connections to
	// complete during graceful shutdown. Zero means wait indefinitely.
	ShutdownTimeout time.Duration
	// StartupBanner controls the optional pretty ASCII startup message printed
	// when Serve starts. It is enabled by default and can be disabled for tests,
	// embedded deployments, JSON-only logs, or process supervisors.
	StartupBanner StartupBannerConfig
}

Config holds server configuration.

type ConfigGeneration

type ConfigGeneration struct {
	// ConfigGeneration is the overall configuration version.
	ConfigGeneration uint64

	// RouteGeneration is the route table version.
	RouteGeneration uint64

	// PolicyGeneration is the security policy version.
	PolicyGeneration uint64

	// CertificateGeneration is the TLS certificate version.
	CertificateGeneration uint64

	// Timestamp is when this generation was created.
	Timestamp time.Time
}

ConfigGeneration tracks a specific configuration revision. Every request records which configuration generation handled it, making deployment failures easy to diagnose.

func (ConfigGeneration) String

func (g ConfigGeneration) String() string

String returns a human-readable representation.

type ConfigReloader

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

ConfigReloader provides atomic, transactional configuration reload. The reload sequence is:

  1. Parse new configuration.
  2. Validate routes and policies.
  3. Compile routing structures.
  4. Load certificates and keys.
  5. Initialize dependencies.
  6. Run health checks.
  7. Swap the complete configuration atomically.
  8. Drain resources belonging to the old revision.
  9. Roll back automatically on failure.

func NewConfigReloader

func NewConfigReloader(app *App) *ConfigReloader

NewConfigReloader creates a configuration reloader for the given app.

func (*ConfigReloader) Generation

func (cr *ConfigReloader) Generation() ConfigGeneration

Generation returns the current configuration generation.

func (*ConfigReloader) OnReload

func (cr *ConfigReloader) OnReload(hook ReloadHook)

OnReload registers a hook that fires after a successful reload.

func (*ConfigReloader) Reload

func (cr *ConfigReloader) Reload(newCfg *Config) ReloadResult

Reload performs an atomic configuration reload. The steps are:

  1. Parse the new configuration.
  2. Validate routes and policies.
  3. Compile routing structures.
  4. Load certificates and keys.
  5. Initialize dependencies.
  6. Run health checks.
  7. Swap the complete configuration atomically.
  8. Drain resources belonging to the old revision.
  9. Roll back automatically on failure.

func (*ConfigReloader) Rollback

func (cr *ConfigReloader) Rollback() error

Rollback reverts to the previous configuration generation.

func (*ConfigReloader) SetDrain

func (cr *ConfigReloader) SetDrain(fn func(old *ConfigGeneration) error)

SetDrain sets a drain function called after successful reload to clean up old resources.

func (*ConfigReloader) SetHealthCheck

func (cr *ConfigReloader) SetHealthCheck(fn func() error)

SetHealthCheck sets a health check function called before reload.

func (*ConfigReloader) SetRollback

func (cr *ConfigReloader) SetRollback(fn func(old *ConfigGeneration) error)

SetRollback sets a rollback function called when reload fails.

func (*ConfigReloader) SetValidation

func (cr *ConfigReloader) SetValidation(fn func(cfg *Config) error)

SetValidation sets a custom validation function called before reload.

type ContentTypeAwareCodec

type ContentTypeAwareCodec interface {
	Codec
	UnmarshalWithContentType(data []byte, contentType string, v any) error
}

ContentTypeAwareCodec is implemented by codecs that need access to media type parameters, for example multipart/form-data; boundary=...

type Cookie struct {
	Name        string
	Value       string
	Path        string
	Domain      string
	MaxAge      int
	Expires     time.Time
	Secure      bool
	HttpOnly    bool
	SameSite    SameSite
	Partitioned bool
}

func (*Cookie) Sign

func (c *Cookie) Sign(secret []byte) error

Sign signs the cookie value with HMAC-SHA256, binding the cookie's Name into the MAC. The signed format is "value.base64_url_hmac".

Binding Name matters: without it, a signature is valid for its value alone regardless of which cookie it's attached to. Two cookies signed with the same secret that ever hold the same value (e.g. "role=admin" and, independently, "flag=admin") would then carry an identical signature — letting an attacker copy a signed value they legitimately received under one cookie name into a different cookie name and have it verify as authentic there too.

func (*Cookie) String

func (c *Cookie) String() string

String returns the Set-Cookie header value for this cookie.

func (*Cookie) Valid

func (c *Cookie) Valid() error

Valid checks RFC 6265 syntax and security invariants for cookie prefixes, SameSite=None, and partitioned cookies.

func (*Cookie) Verify

func (c *Cookie) Verify(secret []byte) bool

Verify checks the HMAC signature on a signed cookie value, requiring it to have been signed for this exact cookie Name (see Sign).

type Ctx

type Ctx interface {
	Next() error
	Method() string
	MethodBytes() []byte
	OriginalURL() string
	Path() string
	Rewrite(target string) error
	Param(name string) string
	Params(name string, defaults ...string) string
	Query(name string, def ...string) string
	Body() []byte
	// StreamBody passes the request body to fn without first buffering it when
	// StreamRequestBody is enabled. In the default mode it reads from Body().
	StreamBody(fn func(io.Reader) error) error
	BodyCopy() []byte
	BodyRaw() []byte
	QueryParser(v any) error
	HeaderParser(v any) error
	Trailer(name string) string
	SetTrailer(key, value string)
	BodyParser(v any) error
	Context() context.Context
	SetContext(ctx context.Context)
	Done() <-chan struct{}
	Err() error
	Deadline() (time.Time, bool)
	TransformBody(fn func([]byte) ([]byte, error))
	AddBodyTransform(fn func([]byte) ([]byte, error))
	Get(name string, defaults ...string) string
	GetReqHeaders() map[string][]string
	GetHeaders() map[string][]string
	ConnectProtocol() string
	Hostname() string
	Locals(key string, value ...any) any
	IP() string
	Status(code int) Ctx
	StatusCode() int
	Set(key, value string)
	SetAltSvc(value string) Ctx
	RequestPreference(name string) bool
	SetPreferenceApplied(value string) Ctx
	Append(key, value string)
	Responded() bool
	Type(mime string) Ctx
	ResponseHeader(name string) string
	GetRespHeader(name string, defaults ...string) string
	GetRespHeaders() map[string][]string
	ResponseBody() []byte
	HasResponseCookies() bool
	FirstCookie() string
	SendString(s string) error
	HTML(s string) error
	SendBytes(b []byte) error
	Send(b []byte) error
	JSON(v any) error
	JSONBytes(b []byte) error
	JSONString(s string) error
	JSONAppend(fn JSONAppendFunc) error
	EchoBody(contentType ...string) error
	EchoJSON(validate ...bool) error
	Render(name string, data any, layout ...string) error
	SendStatus(code int) error
	Redirect(location string, code ...int) error
	RedirectTo(name string, params map[string]string, code ...int) error
	RedirectBack(fallback string, code ...int) error
	Flash(key string, value ...any) any
	// FlashAll retrieves and consumes all pending flash data atomically.
	// Returns nil when there is no flash data. Requires session middleware.
	FlashAll() map[string]any
	// RedirectWithFlash sets one or more flash key/value pairs then redirects.
	// Flash data is available exactly once on the next request.
	RedirectWithFlash(location string, code int, flash map[string]any) error
	App() *App
	ServerOutbox() *Outbox
	ServerInbox() *Inbox
	CaptureResponseBody()
	OnBeforeResponse(fn func(Ctx) error)
	SetCookie(cookie *Cookie)
	GetCookie(name string) string
	DelCookie(name string)
	Problem(p Problem) error
	ProblemDetails(status int, title, detail, typeURI string) error
	Bind(v any) error
	BindJSON(v any) error
	BindQuery(v any) error
	BindForm(v any) error
	BindHeader(v any) error
	SSEvent(event string, data any) error
	ErrorReport(err error) ErrorReport
	ErrorResponse(err error) error
	SafeErrorResponse(err error) error
	Stream(fn func(*StreamWriter) error) error
	StreamLength(size int64, fn func(*StreamWriter) error) error
	SendStream(r io.Reader) error
	SendStreamLength(r io.Reader, size int64) error
	Hijack(handler func(*ResponseConn) error) error
	Upgrade(protocol string, handler func(net.Conn) error) error
	Attachment(filename string) Ctx
	SendFile(filename string) error
	File(filename string) error
	Download(filename string, downloadName ...string) error
	MultipartForm() (*MultipartForm, error)
	FormFile(field string) (*MultipartFile, error)
	SaveFile(file *MultipartFile, dst string) error
	Audit() AuditRecorder
	Ledger(action, resource, resourceID string, before, after []byte) error
	Lifecycle() *RequestLifecycle
	Compensate(fn func(context.Context) error)
	RunCompensations() error
	SSE(fn func(*SSE) error) error
	Reliability() *Reliability
	RunReliableEndpoint(policy ReliabilityPolicy, endpoint HandlerFunc) error
	Queue() Queue
	RequestHeader() *RequestHeader
	RequestPriority() HTTPPriority
	SetResponsePriority(priority HTTPPriority) Ctx
	AutoETag() Ctx
	EarlyHint(uri string) bool
	EarlyHintsWithHeaders(uri string, attrs map[string]string) bool
	Send103EarlyHints(links []string) bool
	SendInformational(status int, headers map[string]string) bool

	// QueryBool returns the query parameter as a bool.
	// "true", "1", "yes" (case-insensitive) → true; everything else → false.
	QueryBool(key string, def ...bool) bool
	// QueryInt returns the query parameter parsed as int, or the default value.
	QueryInt(key string, def ...int) int
	// QueryFloat returns the query parameter parsed as float64, or the default value.
	QueryFloat(key string, def ...float64) float64
	// ParamsInt returns the named route parameter parsed as int, or 0 on error.
	ParamsInt(key string) (int, error)
	// AllParams returns all named route parameters as a map.
	AllParams() map[string]string
	// CookieParser binds cookie values into a struct using the "cookie" tag.
	CookieParser(v any) error
	// ParamsParser binds named route parameters into a struct using the "params" tag.
	ParamsParser(v any) error
	// JSONP sends a JSONP response wrapped in the given callback function.
	JSONP(data any, callback ...string) error
	// Links joins the given URIs into a Link response header field (RFC 8288).
	Links(link ...string)
	// Location sets the Location response header to the given path.
	Location(path string)
	// Fresh checks whether the request is fresh based on ETag/If-None-Match
	// and Last-Modified/If-Modified-Since headers. Returns true when the
	// client cache is still valid and a 304 may be sent.
	Fresh() bool
	// Secure returns true when the connection uses TLS.
	Secure() bool
	// IsFromLocal returns true when the request originates from a loopback address.
	IsFromLocal() bool

	// Vary appends field names to the Vary response header without duplicating existing values.
	Vary(fields ...string)
	// IsXHR returns true when the request was made with XMLHttpRequest (X-Requested-With: XMLHttpRequest).
	IsXHR() bool
	// Protocol returns the request scheme: "https" when the connection is TLS, otherwise "http".
	Protocol() string
	// Subdomains returns subdomain segments of the Host, offset from the right (default 2).
	// e.g. for Host=api.v2.example.com with offset=2 → ["v2", "api"].
	Subdomains(offset ...int) []string
	// BaseURL returns scheme://host (no trailing slash).
	BaseURL() string
	// Accepts returns the best MIME type match from the client's Accept header.
	// Returns the first offered type when the header is absent.
	// Returns "" when none of the offered types are acceptable.
	Accepts(offers ...string) string
	// AcceptsCharsets returns the best charset match from Accept-Charset.
	AcceptsCharsets(offers ...string) string
	// AcceptsEncodings returns the best encoding match from Accept-Encoding.
	AcceptsEncodings(offers ...string) string
	// AcceptsLanguages returns the best language match from Accept-Language.
	AcceptsLanguages(offers ...string) string
	// XML encodes v as XML and sends it with Content-Type application/xml; charset=utf-8.
	XML(v any) error
	// Format performs content-type negotiation from the Accept header and dispatches
	// to the matching handler. Falls through to Next when no handler matches.
	Format(handlers map[string]HandlerFunc) error
	// Range parses the Range request header for a resource of the given total size.
	// Returns nil, nil when no Range header is present (caller should serve the full resource).
	// Returns a 416 status error when the range is syntactically valid but unsatisfiable.
	Range(size int64) ([]ByteRange, error)
	// ClearCookie expires cookies by name. With no arguments all staged response
	// cookies are expired. The name must match the name used when the cookie was set.
	ClearCookie(name ...string)
	// QueryMultiple returns all values for a repeated query parameter.
	QueryMultiple(name string) []string
	// IPs returns all IP addresses from the X-Forwarded-For chain, left to right.
	IPs() []string
	// ClearSiteData sets the Clear-Site-Data response header (e.g. "cache", "cookies", "storage", "executionContexts", "*").
	ClearSiteData(directives ...string)
	// AcceptCH sets the Accept-CH response header for User-Agent Client Hints.
	AcceptCH(hints ...string)
	// CriticalCH sets the Critical-CH response header and adds them to Accept-CH.
	CriticalCH(hints ...string)
	// StaleWhileRevalidate appends the stale-while-revalidate directive to Cache-Control.
	StaleWhileRevalidate(d time.Duration)
	// SendContinue sends an intermediate 100 Continue response.
	SendContinue() error
	// LastEventID returns the Last-Event-ID header or ?lastEventId= query param.
	LastEventID() string
}

Ctx is the public request/response context contract used by handlers and middleware. DefaultCtx is the built-in implementation used by App. Custom implementations can be supplied in tests or adapters by implementing this interface.

type DataPolicy

type DataPolicy struct {
	Sensitivity   string
	Categories    []string
	RedactLogs    bool
	EncryptAtRest bool
	JournalMode   string
	KeyID         string
	Key           []byte
}

Data sensitivity and secure envelope.

type DefaultCtx

type DefaultCtx struct {
	Header RequestHeader
	// contains filtered or unexported fields
}

func (*DefaultCtx) AcceptCH

func (c *DefaultCtx) AcceptCH(hints ...string)

AcceptCH sets the Accept-CH response header for User-Agent Client Hints.

func (*DefaultCtx) Accepts

func (c *DefaultCtx) Accepts(offers ...string) string

Accepts returns the best MIME type match from the client's Accept header. When the header is absent or "*/*", the first offered type is returned. Returns "" when none of the offered types are acceptable (q=0 or no match).

func (*DefaultCtx) AcceptsCharsets

func (c *DefaultCtx) AcceptsCharsets(offers ...string) string

AcceptsCharsets selects the best offered charset from Accept-Charset.

func (*DefaultCtx) AcceptsEncodings

func (c *DefaultCtx) AcceptsEncodings(offers ...string) string

AcceptsEncodings selects the best offered encoding from Accept-Encoding.

func (*DefaultCtx) AcceptsLanguages

func (c *DefaultCtx) AcceptsLanguages(offers ...string) string

AcceptsLanguages selects the best offered language from Accept-Language.

func (*DefaultCtx) AddBodyTransform

func (c *DefaultCtx) AddBodyTransform(fn func([]byte) ([]byte, error))

AddBodyTransform appends a response transformation without replacing an existing middleware transformation.

func (*DefaultCtx) AllParams

func (c *DefaultCtx) AllParams() map[string]string

AllParams returns all named route parameters as a map.

func (*DefaultCtx) App

func (c *DefaultCtx) App() *App

App returns the owning application instance for advanced integrations.

func (*DefaultCtx) Append

func (c *DefaultCtx) Append(key, value string)

Append adds a comma-separated response header value without replacing an existing value. It is useful for fields such as Vary.

func (*DefaultCtx) Attachment

func (c *DefaultCtx) Attachment(filename string) Ctx

Attachment marks a response as a download using a safely encoded filename.

func (*DefaultCtx) Audit

func (c *DefaultCtx) Audit() AuditRecorder

func (*DefaultCtx) AutoETag

func (c *DefaultCtx) AutoETag() Ctx

AutoETag enables automatic ETag calculation and RFC 9110 conditional 304 response handling for the current request.

func (*DefaultCtx) BaseURL

func (c *DefaultCtx) BaseURL() string

BaseURL returns scheme://host with no trailing slash.

func (*DefaultCtx) Bind

func (c *DefaultCtx) Bind(v any) error

func (*DefaultCtx) BindForm

func (c *DefaultCtx) BindForm(v any) error

func (*DefaultCtx) BindHeader

func (c *DefaultCtx) BindHeader(v any) error

func (*DefaultCtx) BindJSON

func (c *DefaultCtx) BindJSON(v any) error

func (*DefaultCtx) BindQuery

func (c *DefaultCtx) BindQuery(v any) error

func (*DefaultCtx) Body

func (c *DefaultCtx) Body() []byte

func (*DefaultCtx) BodyCopy

func (c *DefaultCtx) BodyCopy() []byte

BodyCopy returns a stable copy of the request body. Use it when data must outlive the handler, for example when enqueueing async work.

func (*DefaultCtx) BodyParser

func (c *DefaultCtx) BodyParser(v any) error

func (*DefaultCtx) BodyRaw

func (c *DefaultCtx) BodyRaw() []byte

BodyRaw is the Fiber-compatible name for the unmodified request body.

func (*DefaultCtx) CaptureResponseBody

func (c *DefaultCtx) CaptureResponseBody()

CaptureResponseBody enables a stable in-request response body snapshot for middleware that must inspect or persist the final response (cache, idempotency, request journal). It is intentionally opt-in to keep the hot path zero-copy.

func (*DefaultCtx) ClearCookie

func (c *DefaultCtx) ClearCookie(name ...string)

ClearCookie expires cookies by name. With no arguments, all staged response cookies on this context are expired. To clear a browser-stored cookie the name (and optionally Path/Domain) must match the original Set-Cookie.

func (*DefaultCtx) ClearSiteData

func (c *DefaultCtx) ClearSiteData(directives ...string)

ClearSiteData sets the Clear-Site-Data response header (W3C Clear Site Data specification). Valid directives: "cache", "cookies", "storage", "executionContexts", or "*" (all). Directives are automatically quoted according to the standard.

func (*DefaultCtx) Compensate

func (c *DefaultCtx) Compensate(fn func(context.Context) error)

func (*DefaultCtx) ConnectProtocol

func (c *DefaultCtx) ConnectProtocol() string

ConnectProtocol returns the negotiated protocol for an RFC 8441 extended CONNECT request (the HTTP/2 :protocol pseudo-header, e.g. "websocket"). It returns "" for HTTP/1.1 requests and for HTTP/2 requests that are not extended CONNECT — use it to detect HTTP/2 upgrade-eligible requests without relying on the HTTP/1.1-only Connection/Upgrade headers, which HTTP/2 forbids.

func (*DefaultCtx) Context

func (c *DefaultCtx) Context() context.Context

Context carries request cancellation and middleware deadlines.

func (*DefaultCtx) CookieParser

func (c *DefaultCtx) CookieParser(v any) error

CookieParser binds cookie values into a struct using the "cookie" tag.

func (*DefaultCtx) CriticalCH

func (c *DefaultCtx) CriticalCH(hints ...string)

CriticalCH sets the Critical-CH response header and also adds the hints to Accept-CH.

func (*DefaultCtx) Deadline

func (c *DefaultCtx) Deadline() (time.Time, bool)

Deadline returns the time at which the request context will be cancelled, if a deadline has been set (e.g. via WriteTimeout or the timeout middleware).

func (*DefaultCtx) DelCookie

func (c *DefaultCtx) DelCookie(name string)

DelCookie deletes a cookie by name (sets MaxAge=-1 with an expired date).

func (*DefaultCtx) DelResponseHeader

func (c *DefaultCtx) DelResponseHeader(name string)

DelResponseHeader removes every pending response value with the given name. Set-Cookie is intentionally not removed by this method; cookies are managed through SetCookie/DelCookie so a middleware cannot accidentally erase an authentication transition while hiding application response metadata.

func (*DefaultCtx) Done

func (c *DefaultCtx) Done() <-chan struct{}

Done returns a channel that is closed when the request context is cancelled (timeout, client disconnect, server draining). Handlers should select on this channel alongside their own work to implement cooperative cancellation.

func (*DefaultCtx) Download

func (c *DefaultCtx) Download(filename string, downloadName ...string) error

Download serves a file as an attachment. The optional filename controls the client-visible name without changing the source path.

func (*DefaultCtx) EarlyHint

func (c *DefaultCtx) EarlyHint(uri string) bool

EarlyHint sends an HTTP 103 Early Hints response to hint at resources the server will likely include in the final response. This allows the client to begin fetching resources before the server finishes processing.

Usage:

app.Get("/page", func(c fh.Ctx) error {
    c.EarlyHint("/static/style.css")
    c.EarlyHint("/static/app.js")
    // ... expensive computation ...
    return c.JSON(pageData)
})

func (*DefaultCtx) EarlyHintsWithHeaders

func (c *DefaultCtx) EarlyHintsWithHeaders(uri string, attrs map[string]string) bool

EarlyHintsWithHeaders sends an HTTP 103 Early Hints with custom Link headers and optional headers like rel, as, type, crossorigin.

Usage:

c.EarlyHintsWithHeaders("/font.woff2", map[string]string{
    "rel": "preload", "as": "font", "type": "font/woff2", "crossorigin": "",
})

func (*DefaultCtx) EchoBody

func (c *DefaultCtx) EchoBody(contentType ...string) error

EchoBody sends the request body back without parsing or copying. This is the correct hot-path primitive for proxy, webhook, and raw echo endpoints; do not decode and re-encode JSON just to return the same payload.

func (*DefaultCtx) EchoJSON

func (c *DefaultCtx) EchoJSON(validate ...bool) error

EchoJSON sends the request body back as JSON. By default it trusts upstream validation for maximum throughput. Pass true to validate with the active JSON engine before echoing.

func (*DefaultCtx) Err

func (c *DefaultCtx) Err() error

Err returns nil while the request is still active and a non-nil error (context.Canceled or context.DeadlineExceeded) once the context has been cancelled or its deadline has expired.

func (*DefaultCtx) ErrorReport

func (c *DefaultCtx) ErrorReport(err error) ErrorReport

func (*DefaultCtx) ErrorResponse

func (c *DefaultCtx) ErrorResponse(err error) error

func (*DefaultCtx) File

func (c *DefaultCtx) File(filename string) error

File is an alias for SendFile.

func (*DefaultCtx) FirstCookie

func (c *DefaultCtx) FirstCookie() string

func (*DefaultCtx) Flash

func (c *DefaultCtx) Flash(key string, value ...any) any

Flash stores a value for the next request, or retrieves and consumes it when called without a value. The session middleware must be registered.

func (*DefaultCtx) FlashAll

func (c *DefaultCtx) FlashAll() map[string]any

FlashAll retrieves and consumes all pending flash data atomically. Returns nil when there is no flash data. Requires session middleware.

func (*DefaultCtx) FormFile

func (c *DefaultCtx) FormFile(field string) (*MultipartFile, error)

FormFile returns the first uploaded file for field.

func (*DefaultCtx) Format

func (c *DefaultCtx) Format(handlers map[string]HandlerFunc) error

Format performs content negotiation from the Accept header and dispatches to the matching handler. It sets Content-Type to the matched key before calling the handler. Falls through to Next when no handler matches or offers is empty.

func (*DefaultCtx) Fresh

func (c *DefaultCtx) Fresh() bool

Fresh checks whether the request is fresh based on ETag/If-None-Match and Last-Modified/If-Modified-Since headers.

func (*DefaultCtx) Get

func (c *DefaultCtx) Get(name string, defaults ...string) string

func (*DefaultCtx) GetCookie

func (c *DefaultCtx) GetCookie(name string) string

GetCookie returns the value of a named cookie from the request.

func (*DefaultCtx) GetHeaders

func (c *DefaultCtx) GetHeaders() map[string][]string

GetHeaders is an alias for GetReqHeaders.

func (*DefaultCtx) GetReqHeaders

func (c *DefaultCtx) GetReqHeaders() map[string][]string

GetReqHeaders returns all request header values, preserving repeated fields.

func (*DefaultCtx) GetRespHeader

func (c *DefaultCtx) GetRespHeader(name string, defaults ...string) string

GetRespHeader is the Fiber-compatible alias for ResponseHeader.

func (*DefaultCtx) GetRespHeaders

func (c *DefaultCtx) GetRespHeaders() map[string][]string

GetRespHeaders returns all response headers set on the context.

func (*DefaultCtx) HTML

func (c *DefaultCtx) HTML(s string) error

func (*DefaultCtx) HasResponseCookies

func (c *DefaultCtx) HasResponseCookies() bool

HasResponseCookies reports whether the response currently sets cookies.

func (*DefaultCtx) HeaderBytes

func (c *DefaultCtx) HeaderBytes(name []byte) []byte

HeaderBytes returns a request header value without allocation.

func (*DefaultCtx) HeaderParser

func (c *DefaultCtx) HeaderParser(v any) error

HeaderParser decodes request headers into v using `header` struct tags. Supported target types: *map[string]string, *map[string][]string, or a struct pointer where each exported field is matched by the header name specified in its `header:"name"` tag (case-insensitive). When the tag is absent the lower-cased field name is used. Supported field types are string, []string, int, int64, uint64, float64, bool, and *string.

func (*DefaultCtx) Hijack

func (c *DefaultCtx) Hijack(handler func(*ResponseConn) error) error

Hijack runs handler synchronously on the raw HTTP/1.x connection. Reads first consume bytes already buffered after the request. The handler owns the protocol conversation until it returns. The provided ResponseConn has WriteHeader, SetHeader, and Write methods for clean HTTP response construction — use StatusText and header constants.

func (*DefaultCtx) Hostname

func (c *DefaultCtx) Hostname() string

Hostname returns the request host without its port.

func (*DefaultCtx) IP

func (c *DefaultCtx) IP() string

func (*DefaultCtx) IPs

func (c *DefaultCtx) IPs() []string

IPs returns all IP addresses from the X-Forwarded-For header, left to right. Returns nil when the header is absent.

func (*DefaultCtx) IsFromLocal

func (c *DefaultCtx) IsFromLocal() bool

IsFromLocal returns true when the request originates from a loopback address.

func (*DefaultCtx) IsXHR

func (c *DefaultCtx) IsXHR() bool

IsXHR returns true when the request carries X-Requested-With: XMLHttpRequest.

func (*DefaultCtx) JSON

func (c *DefaultCtx) JSON(v any) error

JSON writes v as application/json using the active JSON engine. Types that implement JSONAppender are encoded directly into the response buffer, avoiding a marshal allocation and a second response-copy on the normal hot path.

func (*DefaultCtx) JSONAppend

func (c *DefaultCtx) JSONAppend(fn JSONAppendFunc) error

JSONAppend writes JSON generated directly into fh's pooled response buffer. This is the preferred hot-path API for small dynamic JSON responses because it avoids string concatenation, reflection, and a second body copy.

func (*DefaultCtx) JSONBytes

func (c *DefaultCtx) JSONBytes(b []byte) error

JSONBytes sends an already encoded JSON document without re-marshalling.

func (*DefaultCtx) JSONP

func (c *DefaultCtx) JSONP(data any, callback ...string) error

JSONP sends a JSONP response wrapped in the given callback function. If no callback is provided, defaults to "callback".

func (*DefaultCtx) JSONString

func (c *DefaultCtx) JSONString(s string) error

JSONString sends an already encoded JSON document without re-marshalling.

func (*DefaultCtx) LastEventID

func (c *DefaultCtx) LastEventID() string

LastEventID returns the Last-Event-ID header sent by the client when reconnecting, or the ?lastEventId= query parameter as a fallback.

func (*DefaultCtx) Ledger

func (c *DefaultCtx) Ledger(action, resource, resourceID string, before, after []byte) error

func (*DefaultCtx) Lifecycle

func (c *DefaultCtx) Lifecycle() *RequestLifecycle
func (c *DefaultCtx) Links(link ...string)

Links joins the given URIs into a Link response header field (RFC 8288).

func (*DefaultCtx) Locals

func (c *DefaultCtx) Locals(key string, value ...any) any

func (*DefaultCtx) Location

func (c *DefaultCtx) Location(path string)

Location sets the Location response header to the given path.

func (*DefaultCtx) Method

func (c *DefaultCtx) Method() string

func (*DefaultCtx) MethodBytes

func (c *DefaultCtx) MethodBytes() []byte

MethodBytes returns the request method without allocation. The slice is valid only during the handler lifetime.

func (*DefaultCtx) MultipartForm

func (c *DefaultCtx) MultipartForm() (*MultipartForm, error)

MultipartForm parses and caches the request's multipart form.

func (*DefaultCtx) Next

func (c *DefaultCtx) Next() error

Next continues the current middleware chain. A handler may return without calling Next to stop the chain. The index-based implementation avoids the per-request recursive closure used by many small middleware implementations.

func (*DefaultCtx) OnBeforeResponse

func (c *DefaultCtx) OnBeforeResponse(fn func(Ctx) error)

OnBeforeResponse registers a one-shot hook run immediately before response headers are encoded. It is intended for transactional middleware such as sessions that must persist before Set-Cookie reaches the wire.

func (*DefaultCtx) OriginalURL

func (c *DefaultCtx) OriginalURL() string

OriginalURL returns the request target as it arrived, before any Rewrite. The name mirrors Fiber's Ctx API.

func (*DefaultCtx) OriginalURLBytes

func (c *DefaultCtx) OriginalURLBytes() []byte

OriginalURLBytes returns the exact request target from the request line when available, without allocation. It is valid only during the handler lifetime.

func (*DefaultCtx) Param

func (c *DefaultCtx) Param(name string) string

func (*DefaultCtx) Params

func (c *DefaultCtx) Params(name string, defaults ...string) string

Params is the Fiber-compatible alias for Param. If the parameter is absent, the optional default value is returned.

func (*DefaultCtx) ParamsInt

func (c *DefaultCtx) ParamsInt(key string) (int, error)

ParamsInt returns the named route parameter parsed as int, or 0 on error.

func (*DefaultCtx) ParamsParser

func (c *DefaultCtx) ParamsParser(v any) error

ParamsParser binds named route parameters into a struct using the "params" tag.

func (*DefaultCtx) Path

func (c *DefaultCtx) Path() string

func (*DefaultCtx) PathBytes

func (c *DefaultCtx) PathBytes() []byte

PathBytes returns the route path without allocation. The slice is valid only during the handler lifetime.

func (*DefaultCtx) Problem

func (c *DefaultCtx) Problem(p Problem) error

func (*DefaultCtx) ProblemDetails

func (c *DefaultCtx) ProblemDetails(status int, title, detail, typeURI string) error

func (*DefaultCtx) Protocol

func (c *DefaultCtx) Protocol() string

Protocol returns "https" when the connection uses TLS, otherwise "http".

func (*DefaultCtx) Push

func (c *DefaultCtx) Push(path string, method string, headers map[string]string) bool

Push sends an HTTP/2 PUSH_PROMISE frame to the client for the given path. Returns false if push is not possible (disabled, too many promises, or client has disabled server push via SETTINGS_ENABLE_PUSH=0).

Usage:

app.Get("/page", func(c fh.Ctx) error {
    dc := c.(*fh.DefaultCtx)
    dc.Push("/static/style.css", "GET", nil)
    dc.Push("/static/app.js", "GET", nil)
    return c.JSON(pageData)
})

func (*DefaultCtx) PushDocument

func (c *DefaultCtx) PushDocument(path string) bool

PushDocument is a convenience helper to push a document (JSON, XML, etc.).

func (*DefaultCtx) PushFont

func (c *DefaultCtx) PushFont(path string) bool

PushFont is a convenience helper to push a font file.

func (*DefaultCtx) PushImage

func (c *DefaultCtx) PushImage(path string) bool

PushImage is a convenience helper to push an image file.

func (*DefaultCtx) PushResource

func (c *DefaultCtx) PushResource(path string, method string, headers map[string]string) bool

PushResource pushes resources during HTTP/2 or early hints during HTTP/1.1. This is a convenience method that automatically selects the right mechanism.

func (*DefaultCtx) PushScript

func (c *DefaultCtx) PushScript(path string) bool

PushScript is a convenience helper to push a JavaScript file.

func (*DefaultCtx) PushStylesheet

func (c *DefaultCtx) PushStylesheet(path string) bool

PushStylesheet is a convenience helper to push a CSS file.

func (*DefaultCtx) Query

func (c *DefaultCtx) Query(name string, def ...string) string

func (*DefaultCtx) QueryBool

func (c *DefaultCtx) QueryBool(key string, def ...bool) bool

QueryBool returns the query parameter as a bool. "true", "1", "yes" (case-insensitive) → true; everything else → false.

func (*DefaultCtx) QueryBytes

func (c *DefaultCtx) QueryBytes(name []byte) []byte

QueryBytes returns a raw query parameter value without decoding or allocation. Use Query when percent-decoding/string ownership is required.

func (*DefaultCtx) QueryFloat

func (c *DefaultCtx) QueryFloat(key string, def ...float64) float64

QueryFloat returns the query parameter parsed as float64, or the default value.

func (*DefaultCtx) QueryInt

func (c *DefaultCtx) QueryInt(key string, def ...int) int

QueryInt returns the query parameter parsed as int, or the default value.

func (*DefaultCtx) QueryMultiple

func (c *DefaultCtx) QueryMultiple(name string) []string

QueryMultiple returns all values for a repeated query parameter. For /search?tag=go&tag=web it returns ["go", "web"].

func (*DefaultCtx) QueryParser

func (c *DefaultCtx) QueryParser(v any) error

QueryParser decodes the query string into v. The target type should be *map[string]any for unstructured access; struct decoding is not yet supported. QueryParser decodes the query string into v. Supports the same formats as form-encoded bodies (nested keys via bracket notation, arrays, etc.). Target should be *map[string]any or *any.

func (*DefaultCtx) Queue

func (c *DefaultCtx) Queue() Queue

Queue returns the request's configured durable queue.

func (*DefaultCtx) Range

func (c *DefaultCtx) Range(size int64) ([]ByteRange, error)

Range parses the Range request header for a resource of the given total size. Returns nil, nil when no Range header is present (serve the full resource). Returns a 416 error when the header is present but unsatisfiable.

func (*DefaultCtx) Redirect

func (c *DefaultCtx) Redirect(location string, code ...int) error

func (*DefaultCtx) RedirectBack

func (c *DefaultCtx) RedirectBack(fallback string, code ...int) error

RedirectBack redirects to a same-origin Referer, or to fallback when the Referer is absent, malformed, or points at another host.

func (*DefaultCtx) RedirectTo

func (c *DefaultCtx) RedirectTo(name string, params map[string]string, code ...int) error

RedirectTo redirects to a named route. Route parameters are substituted and additional values become query parameters.

func (*DefaultCtx) RedirectWithFlash

func (c *DefaultCtx) RedirectWithFlash(location string, code int, flash map[string]any) error

RedirectWithFlash sets one or more flash key/value pairs then redirects. Flash data is available exactly once on the next request.

func (*DefaultCtx) Reliability

func (c *DefaultCtx) Reliability() *Reliability

Reliability returns the request's configured reliability runtime.

func (*DefaultCtx) Render

func (c *DefaultCtx) Render(name string, data any, layout ...string) error

func (*DefaultCtx) RequestHeader

func (c *DefaultCtx) RequestHeader() *RequestHeader

func (*DefaultCtx) RequestPreference

func (c *DefaultCtx) RequestPreference(name string) bool

RequestPreference reports whether the Prefer request field contains the named preference, ignoring optional parameters and casing.

func (*DefaultCtx) RequestPriority

func (c *DefaultCtx) RequestPriority() HTTPPriority

RequestPriority returns the parsed Priority request field. Invalid or missing parameters use RFC 9218's defaults.

func (*DefaultCtx) Responded

func (c *DefaultCtx) Responded() bool

Responded reports whether response headers have already been written.

func (*DefaultCtx) ResponseBody

func (c *DefaultCtx) ResponseBody() []byte

ResponseBody returns the currently prepared response body snapshot. It is primarily used by reliability/idempotency middleware. The slice is valid only during the request lifecycle; copy it if it must be retained.

func (*DefaultCtx) ResponseHeader

func (c *DefaultCtx) ResponseHeader(name string) string

ResponseHeader returns a response header set so far.

func (*DefaultCtx) Rewrite

func (c *DefaultCtx) Rewrite(target string) error

Rewrite updates the request URI and asks the application to route it again. It is intended for rewrite middleware and is bounded by the application to prevent rewrite loops.

func (*DefaultCtx) RunCompensations

func (c *DefaultCtx) RunCompensations() error

func (*DefaultCtx) RunReliableEndpoint

func (c *DefaultCtx) RunReliableEndpoint(policy ReliabilityPolicy, endpoint HandlerFunc) error

RunReliableEndpoint applies a reliability policy around an endpoint handler. Endpoint construction itself lives in mw/reliability.

func (*DefaultCtx) SSE

func (c *DefaultCtx) SSE(fn func(*SSE) error) error

SSE starts a persistent Server-Sent Events stream, setting standard headers and passing an *SSE stream controller to fn.

func (*DefaultCtx) SSEvent

func (c *DefaultCtx) SSEvent(event string, data any) error

func (*DefaultCtx) SafeErrorResponse

func (c *DefaultCtx) SafeErrorResponse(err error) error

SafeErrorResponse classifies and writes err. It never lets a secondary render failure escape to the client.

func (*DefaultCtx) SaveFile

func (c *DefaultCtx) SaveFile(file *MultipartFile, dst string) error

SaveFile persists an uploaded file to an explicit destination.

func (*DefaultCtx) Secure

func (c *DefaultCtx) Secure() bool

Secure returns true when the connection uses TLS.

func (*DefaultCtx) Send

func (c *DefaultCtx) Send(b []byte) error

func (*DefaultCtx) Send103EarlyHints

func (c *DefaultCtx) Send103EarlyHints(links []string) bool

Send103EarlyHints writes an HTTP 103 Early Hints response for HTTP/1.1 connections.

func (*DefaultCtx) SendBytes

func (c *DefaultCtx) SendBytes(b []byte) error

func (*DefaultCtx) SendContinue

func (c *DefaultCtx) SendContinue() error

SendContinue sends an intermediate HTTP/1.1 100 Continue response before the final response.

func (*DefaultCtx) SendFile

func (c *DefaultCtx) SendFile(filename string) error

SendFile serves one file from disk with MIME detection, ETag, Last-Modified, conditional requests, and byte ranges.

func (*DefaultCtx) SendInformational

func (c *DefaultCtx) SendInformational(status int, headers map[string]string) bool

func (*DefaultCtx) SendStatus

func (c *DefaultCtx) SendStatus(code int) error

func (*DefaultCtx) SendStream

func (c *DefaultCtx) SendStream(r io.Reader) error

SendStream copies r to a streamed response using a fixed scratch buffer.

func (*DefaultCtx) SendStreamLength

func (c *DefaultCtx) SendStreamLength(r io.Reader, size int64) error

SendStreamLength copies r without buffering it in memory and advertises a known length when size is non-negative.

func (*DefaultCtx) SendString

func (c *DefaultCtx) SendString(s string) error

func (*DefaultCtx) ServerInbox

func (c *DefaultCtx) ServerInbox() *Inbox

ServerInbox returns the reliability inbox for the current app.

func (*DefaultCtx) ServerOutbox

func (c *DefaultCtx) ServerOutbox() *Outbox

ServerOutbox returns the reliability outbox for the current app.

func (*DefaultCtx) Set

func (c *DefaultCtx) Set(key, value string)

func (*DefaultCtx) SetAltSvc

func (c *DefaultCtx) SetAltSvc(value string) Ctx

func (*DefaultCtx) SetClientIP

func (c *DefaultCtx) SetClientIP(value string)

SetClientIP updates the effective request address. Applications should use the package-level SetClientIP helper or mw/realip so input is validated.

func (*DefaultCtx) SetContext

func (c *DefaultCtx) SetContext(ctx context.Context)

func (*DefaultCtx) SetCookie

func (c *DefaultCtx) SetCookie(cookie *Cookie)

SetCookie adds a Set-Cookie header to the response.

func (*DefaultCtx) SetEnablePush

func (c *DefaultCtx) SetEnablePush(enabled bool)

SetEnablePush configures whether server push is allowed on this HTTP/2 connection.

func (*DefaultCtx) SetPreferenceApplied

func (c *DefaultCtx) SetPreferenceApplied(value string) Ctx

SetPreferenceApplied records the preference applied by the response.

func (*DefaultCtx) SetRequestBody

func (c *DefaultCtx) SetRequestBody(body []byte)

SetRequestBody replaces the decoded body visible through Body and BodyParser.

func (*DefaultCtx) SetResponsePriority

func (c *DefaultCtx) SetResponsePriority(priority HTTPPriority) Ctx

SetResponsePriority sets a validated RFC 9218 Priority response field.

func (*DefaultCtx) SetTrailer

func (c *DefaultCtx) SetTrailer(key, value string)

SetTrailer sets a response trailer header. Trailers are sent after the chunked body (HTTP/1.1) or as trailing HEADERS (HTTP/2). The trailer name should also be announced via the Trailer response header.

func (*DefaultCtx) StaleWhileRevalidate

func (c *DefaultCtx) StaleWhileRevalidate(d time.Duration)

StaleWhileRevalidate appends the stale-while-revalidate directive in seconds to Cache-Control.

func (*DefaultCtx) Status

func (c *DefaultCtx) Status(code int) Ctx

func (*DefaultCtx) StatusCode

func (c *DefaultCtx) StatusCode() int

StatusCode returns the current response status code. Used by middleware to inspect the status after calling Next().

func (*DefaultCtx) Stream

func (c *DefaultCtx) Stream(fn func(*StreamWriter) error) error

Stream starts a streaming response and invokes fn synchronously. The final chunk is always written, including when fn returns an error.

func (*DefaultCtx) StreamBody

func (c *DefaultCtx) StreamBody(fn func(io.Reader) error) error

StreamBody consumes the request body incrementally when request-body streaming is enabled. It falls back to a reader over the already-buffered body for applications using the default mode.

func (*DefaultCtx) StreamLength

func (c *DefaultCtx) StreamLength(size int64, fn func(*StreamWriter) error) error

StreamLength starts a streaming response with a known body length. HTTP/1.1 can keep the connection reusable without chunked framing; HTTP/2 continues to use native DATA frames. The callback is invoked synchronously.

func (*DefaultCtx) Subdomains

func (c *DefaultCtx) Subdomains(offset ...int) []string

Subdomains returns the subdomain segments of the Host header, ordered from leftmost (closest to the label boundary) to rightmost. offset (default 2) controls how many right-hand labels (e.g. "example.com") are skipped. For Host=api.v2.example.com with offset=2 → ["api", "v2"].

func (*DefaultCtx) Trailer

func (c *DefaultCtx) Trailer(name string) string

Trailer returns a decoded chunked request trailer by name.

func (*DefaultCtx) TransformBody

func (c *DefaultCtx) TransformBody(fn func([]byte) ([]byte, error))

TransformBody installs a buffered response transformation. It is intended for middleware such as gzip compression and does not affect Stream output.

func (*DefaultCtx) Type

func (c *DefaultCtx) Type(mime string) Ctx

func (*DefaultCtx) Upgrade

func (c *DefaultCtx) Upgrade(protocol string, handler func(net.Conn) error) error

Upgrade switches an HTTP/1.1 connection to another protocol. Over HTTP/2 it transparently uses an RFC 8441 extended CONNECT tunnel instead (see upgradeH2) when the request negotiated one, so the same handler works unmodified for both HTTP/1.1 and HTTP/2 clients.

func (*DefaultCtx) Vary

func (c *DefaultCtx) Vary(fields ...string)

Vary appends field names to the Vary response header without duplicating existing tokens. It is safe to call multiple times.

func (*DefaultCtx) XML

func (c *DefaultCtx) XML(v any) error

XML encodes v to XML and sends it with Content-Type: application/xml; charset=utf-8.

type DurableQueue

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

func NewDurableQueue

func NewDurableQueue(cfg DurableQueueConfig, storage QueueStorage) *DurableQueue

func OpenDurableQueue

func OpenDurableQueue(cfg DurableQueueConfig) (*DurableQueue, error)

func (*DurableQueue) Close

func (q *DurableQueue) Close() error

func (*DurableQueue) DiscardFailed

func (q *DurableQueue) DiscardFailed(ctx context.Context, id string) error

func (*DurableQueue) Enqueue

func (q *DurableQueue) Enqueue(jobType string, payload any, headers ...map[string]string) (string, error)

func (*DurableQueue) EnqueueDelayed

func (q *DurableQueue) EnqueueDelayed(jobType string, payload any, runAt time.Time, headers ...map[string]string) (string, error)

func (*DurableQueue) EnqueueJob

func (q *DurableQueue) EnqueueJob(spec QueueJob, payload any, headers ...map[string]string) (string, error)

func (*DurableQueue) EnqueuePriority

func (q *DurableQueue) EnqueuePriority(jobType string, payload any, priority int, headers ...map[string]string) (string, error)

func (*DurableQueue) EnqueueWithKey

func (q *DurableQueue) EnqueueWithKey(jobType string, payload any, concurrencyKey string, headers ...map[string]string) (string, error)

func (*DurableQueue) ListJobs

func (q *DurableQueue) ListJobs(ctx context.Context, state string, limit int) ([]QueueJobSnapshot, error)

ListJobs returns queue jobs for admin/ops usage when the storage supports it. state may be empty, pending, processing, done or failed.

func (*DurableQueue) PurgeJobs

func (q *DurableQueue) PurgeJobs(ctx context.Context, state string, before time.Time, limit int) (int, error)

func (*DurableQueue) Recover

func (q *DurableQueue) Recover() error

func (*DurableQueue) Register

func (q *DurableQueue) Register(jobType string, handler QueueHandler)

func (*DurableQueue) RetryFailed

func (q *DurableQueue) RetryFailed(ctx context.Context, id string) error

func (*DurableQueue) Start

func (q *DurableQueue) Start() error

func (*DurableQueue) Stats

func (q *DurableQueue) Stats() (QueueStats, error)

func (*DurableQueue) Storage

func (q *DurableQueue) Storage() QueueStorage

type DurableQueueConfig

type DurableQueueConfig struct {
	Dir                   string
	Workers               int
	MaxAttempts           int
	PollInterval          time.Duration
	Backoff               time.Duration
	ConcurrencyLimitByKey bool
	LogError              func(msg string, args ...any)
}

type EncoderCodec

type EncoderCodec interface {
	Codec
	Marshal(v any) ([]byte, error)
}

EncoderCodec is optional. It lets the same registry support response encoding.

type EndpointSelector

type EndpointSelector interface {
	Next(*http.Request) (*url.URL, error)
	Report(*url.URL, *http.Response, error)
}

EndpointSelector supports simple client-side service discovery / load balancing.

type Environment

type Environment string

Environment controls how much diagnostic information is exposed to clients.

const (
	EnvProduction  Environment = "production"
	EnvStaging     Environment = "staging"
	EnvDevelopment Environment = "development"
	EnvTest        Environment = "test"
)

type ErrorDefinition

type ErrorDefinition struct {
	Status    int       `json:"status"`
	Code      string    `json:"code"`
	Message   string    `json:"message"`
	Kind      ErrorKind `json:"kind"`
	Retryable bool      `json:"retryable"`
}

ErrorDefinition describes a built-in error for documentation generators.

func ErrorCatalog

func ErrorCatalog() []ErrorDefinition

type ErrorHandler

type ErrorHandler func(Ctx, error)

ErrorHandler handles errors returned from route handlers and middleware.

type ErrorKind

type ErrorKind string

ErrorKind classifies failures for policy, metrics, alerting, and retry logic.

const (
	KindBadRequest     ErrorKind = "bad_request"
	KindAuth           ErrorKind = "auth"
	KindPermission     ErrorKind = "permission"
	KindNotFound       ErrorKind = "not_found"
	KindConflict       ErrorKind = "conflict"
	KindValidation     ErrorKind = "validation"
	KindRateLimit      ErrorKind = "rate_limit"
	KindTimeout        ErrorKind = "timeout"
	KindDependency     ErrorKind = "dependency"
	KindCapacity       ErrorKind = "capacity"
	KindPanic          ErrorKind = "panic"
	KindInternal       ErrorKind = "internal"
	KindProtocol       ErrorKind = "protocol"
	KindUnavailable    ErrorKind = "unavailable"
	KindNotImplemented ErrorKind = "not_implemented"
)

type ErrorOptions

type ErrorOptions struct {
	Environment      Environment
	ExposeDebug      bool
	ExposeStackTrace bool
	ExposeCauses     bool
	ProblemTypeBase  string
	IncludeRequestID bool
	IncludeTimestamp bool
	IncludeInstance  bool
	LogInternal      bool
	Redact           func(string) string
}

ErrorOptions controls problem-detail rendering and debug friendliness.

type ErrorReport

type ErrorReport struct {
	Error     *HTTPError
	Problem   Problem
	RequestID string
	Timestamp time.Time
	Path      string
	Method    string
	RemoteIP  string
	Stack     []byte
	Cause     string
}

ErrorReport is the fully classified server-side view of an error.

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity identifies operational urgency without changing the HTTP status.

const (
	SeverityInfo     ErrorSeverity = "info"
	SeverityWarning  ErrorSeverity = "warning"
	SeverityError    ErrorSeverity = "error"
	SeverityCritical ErrorSeverity = "critical"
)

type Extractor

type Extractor[T any] func(Ctx) (T, bool, error)

Extractor resolves a value from the current request context. Extractors are intentionally small functions so applications can compose identity and authorization inputs from headers, route params, query strings, body fields, locals, sessions, JWT claims, or any other Ctx-backed source.

func BodyCSV

func BodyCSV(path string) Extractor[[]string]

func BodyField

func BodyField(path string) Extractor[any]

func BodyString

func BodyString(path string) Extractor[string]

func FirstString

func FirstString(extractors ...Extractor[string]) Extractor[string]

func FirstStrings

func FirstStrings(extractors ...Extractor[[]string]) Extractor[[]string]

func HeaderCSV

func HeaderCSV(name string) Extractor[[]string]

HeaderCSV reads a comma-separated list from name and trusts it as-is. See the WARNING on HeaderString: this is unverified client input and must not be used for Roles/Scopes/Permissions unless a trusted upstream guarantees the header cannot be set by the caller directly.

func HeaderString

func HeaderString(name string) Extractor[string]

HeaderString reads name directly from the request and trusts it as-is.

WARNING: this is a raw client input, not an authentication result. Wiring it straight into ID/TenantID/Roles (e.g. via PrincipalExtractors or TenantResolver) lets any caller set their own identity, tenant, or roles by sending the header themselves — there is no verification step here, unlike a verified bearer-token integration or mw/mtls (TLS-verified certificate). Only use HeaderString for identity/authorization fields when a trusted upstream (e.g. an API gateway or sidecar on a network path the caller cannot reach directly) strips or overwrites this header before it reaches fh; otherwise prefer an extractor backed by a verified source (verified bearer-token claims, an mTLS subject, or a session store).

func LocalString

func LocalString(key string) Extractor[string]

func ParamString

func ParamString(name string) Extractor[string]

func PrincipalExtractor

func PrincipalExtractor(ex PrincipalExtractors) Extractor[Principal]

PrincipalExtractor returns a reusable extractor for a Principal composed from field extractors.

func PrincipalPermissionsExtractor

func PrincipalPermissionsExtractor() Extractor[[]string]

func PrincipalRolesExtractor

func PrincipalRolesExtractor() Extractor[[]string]

func PrincipalScopesExtractor

func PrincipalScopesExtractor() Extractor[[]string]

func PrincipalTenantExtractor

func PrincipalTenantExtractor() Extractor[string]

func QueryCSV

func QueryCSV(name string) Extractor[[]string]

func QueryString

func QueryString(name string) Extractor[string]

func StaticString

func StaticString(value string) Extractor[string]

func StringFrom

func StringFrom(ex Extractor[any]) Extractor[string]

func StringsFrom

func StringsFrom(ex Extractor[any]) Extractor[[]string]

func TenantExtractor

func TenantExtractor(sources ...Extractor[string]) Extractor[string]

TenantExtractor resolves a tenant ID, preferring the authenticated Principal's TenantID and any value already stored in Locals. The default fallback, HeaderString("X-Tenant-ID"), trusts a raw client header — only safe when a trusted upstream strips/overwrites that header before it reaches fh. In multi-tenant deployments without such an upstream, pass explicit sources that omit the header fallback (or validate it against a known-tenant list downstream) to prevent cross-tenant access via a spoofed X-Tenant-ID.

type FieldError

type FieldError struct {
	Field   string `json:"field"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

type FileAuditSink

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

func OpenFileAuditSink

func OpenFileAuditSink(path string) (*FileAuditSink, error)

func (*FileAuditSink) Close

func (s *FileAuditSink) Close() error

func (*FileAuditSink) Path

func (s *FileAuditSink) Path() string

func (*FileAuditSink) WriteAudit

func (s *FileAuditSink) WriteAudit(ctx context.Context, e AuditEvent) error

type FileQueueStorage

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

func OpenFileQueueStorage

func OpenFileQueueStorage(cfg FileQueueStorageConfig) (*FileQueueStorage, error)

func (*FileQueueStorage) Claim

func (s *FileQueueStorage) Claim(ctx context.Context, now time.Time) (*QueueJob, error)

func (*FileQueueStorage) Close

func (s *FileQueueStorage) Close() error

func (*FileQueueStorage) Complete

func (s *FileQueueStorage) Complete(ctx context.Context, job *QueueJob) error

func (*FileQueueStorage) Dir

func (s *FileQueueStorage) Dir() string

func (*FileQueueStorage) DiscardFailed

func (s *FileQueueStorage) DiscardFailed(ctx context.Context, id string) error

func (*FileQueueStorage) Enqueue

func (s *FileQueueStorage) Enqueue(ctx context.Context, job *QueueJob) error

func (*FileQueueStorage) Fail

func (s *FileQueueStorage) Fail(ctx context.Context, job *QueueJob, cause error) error

func (*FileQueueStorage) ListJobs

func (s *FileQueueStorage) ListJobs(ctx context.Context, state string, limit int) ([]QueueJobSnapshot, error)

func (*FileQueueStorage) PurgeJobs

func (s *FileQueueStorage) PurgeJobs(ctx context.Context, state string, before time.Time, limit int) (int, error)

func (*FileQueueStorage) Recover

func (s *FileQueueStorage) Recover(ctx context.Context) error

func (*FileQueueStorage) RequeueFailed

func (s *FileQueueStorage) RequeueFailed(ctx context.Context, id string) error

func (*FileQueueStorage) Retry

func (s *FileQueueStorage) Retry(ctx context.Context, job *QueueJob, cause error, backoff time.Duration) error

func (*FileQueueStorage) Stats

func (s *FileQueueStorage) Stats(ctx context.Context) (QueueStats, error)

type FileQueueStorageConfig

type FileQueueStorageConfig struct {
	Dir      string
	LogError func(msg string, args ...any)
}

FileQueueStorage is the default file/directory based QueueStorage.

type Form

type Form struct {
	Values url.Values
	Tree   map[string]any
}

Form is the decoded representation of application/x-www-form-urlencoded. Values stores exact repeated-key values. Tree stores bracket-notation nesting.

func (Form) Bool

func (f Form) Bool(key string) (bool, error)

Bool parses the first value for key.

func (Form) First

func (f Form) First(key string) string

First returns the first value for key, or empty string.

func (Form) Float64

func (f Form) Float64(key string) (float64, error)

Float64 parses the first value for key.

func (Form) Int

func (f Form) Int(key string) (int, error)

Int parses the first value for key.

func (Form) Int64

func (f Form) Int64(key string) (int64, error)

Int64 parses the first value for key.

func (Form) Strings

func (f Form) Strings(key string) []string

Strings returns all values for key.

func (Form) Uint64

func (f Form) Uint64(key string) (uint64, error)

Uint64 parses the first value for key.

type FormBinder

type FormBinder interface {
	BindForm(Form) error
}

FormBinder allows applications to bind form data into structs without this package using reflection. Implement this on DTOs when you need typed binding.

type FutureResponse

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

Async and batch helpers.

func (*FutureResponse) Await

func (f *FutureResponse) Await(ctx context.Context) (*Response, error)

type Group

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

Group is a set of routes sharing a common path prefix and middleware.

func (*Group) All

func (g *Group) All(path string, handlers ...HandlerFunc) *Group

func (*Group) AllTyped

func (g *Group) AllTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Connect

func (g *Group) Connect(path string, handlers ...HandlerFunc) *Group

func (*Group) ConnectTyped

func (g *Group) ConnectTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Delete

func (g *Group) Delete(path string, handlers ...HandlerFunc) *Group

func (*Group) DeleteTyped

func (g *Group) DeleteTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Get

func (g *Group) Get(path string, handlers ...HandlerFunc) *Group

func (*Group) GetTyped

func (g *Group) GetTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Group

func (g *Group) Group(prefix string, handlers ...HandlerFunc) *Group

Group creates a sub-group under this group's prefix.

func (*Group) Head

func (g *Group) Head(path string, handlers ...HandlerFunc) *Group

func (*Group) HeadTyped

func (g *Group) HeadTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Meta

func (g *Group) Meta(key string, val any) *Group

Meta attaches key-value metadata to the most recently registered route in this group.

func (*Group) Mount

func (g *Group) Mount(prefix string, sub *App) *Group

Mount mounts a sub-App onto a path prefix inside this group.

func (*Group) Name

func (g *Group) Name(name string) *Group

Name names the most recently registered route in this group.

func (*Group) Options

func (g *Group) Options(path string, handlers ...HandlerFunc) *Group

func (*Group) OptionsTyped

func (g *Group) OptionsTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Patch

func (g *Group) Patch(path string, handlers ...HandlerFunc) *Group

func (*Group) PatchTyped

func (g *Group) PatchTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Post

func (g *Group) Post(path string, handlers ...HandlerFunc) *Group

func (*Group) PostTyped

func (g *Group) PostTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Purge

func (g *Group) Purge(path string, handlers ...HandlerFunc) *Group

func (*Group) Put

func (g *Group) Put(path string, handlers ...HandlerFunc) *Group

func (*Group) PutTyped

func (g *Group) PutTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Query

func (g *Group) Query(path string, handlers ...HandlerFunc) *Group

func (*Group) QueryTyped

func (g *Group) QueryTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Report

func (g *Group) Report(path string, handlers ...HandlerFunc) *Group

func (*Group) Search

func (g *Group) Search(path string, handlers ...HandlerFunc) *Group

func (*Group) Static

func (g *Group) Static(prefix, root string, config ...StaticConfig) *Group

Static registers a GET route that serves files from root on disk.

func (*Group) StaticFS

func (g *Group) StaticFS(prefix string, filesystem fs.FS, config ...StaticConfig) *Group

StaticFS registers a GET route that serves files from an fs.FS (embed.FS, etc.).

func (*Group) Tag

func (g *Group) Tag(tags ...string) *Group

Tag attaches tags to the most recently registered route in this group.

func (*Group) Trace

func (g *Group) Trace(path string, handlers ...HandlerFunc) *Group

func (*Group) TraceTyped

func (g *Group) TraceTyped(path string, handler any, middleware ...HandlerFunc) *Group

func (*Group) Use

func (g *Group) Use(handlers ...HandlerFunc) *Group

Use adds middleware scoped to this group.

type HTTPError

type HTTPError struct {
	Status    int
	Code      string
	Message   string
	Err       error
	Details   any
	Headers   map[string]string
	Kind      ErrorKind
	Severity  ErrorSeverity
	Retryable bool
	Meta      map[string]any
}

HTTPError is a typed handler error. Message is safe to expose to clients; Err retains the private cause for logging and errors.Is/errors.As.

func BadRequest

func BadRequest(message string) *HTTPError

func Conflict

func Conflict(message string) *HTTPError

func DependencyFailure

func DependencyFailure(message string) *HTTPError

func ErrorResponse

func ErrorResponse(code, message string, status int) *HTTPError

ErrorResponse creates a typed error response.

func Forbidden

func Forbidden(message string) *HTTPError

func InternalError

func InternalError(err error) *HTTPError

func MethodNotAllowed

func MethodNotAllowed(message string) *HTTPError

func NewError

func NewError(status int, message ...string) *HTTPError

NewError constructs an HTTPError from a numeric status code and message. The error code string is derived automatically from the status reason. This is a Fiber-compatible convenience constructor; prefer the typed factory functions (BadRequest, NotFound, …) in new code.

func NewHTTPError

func NewHTTPError(status int, code, message string) *HTTPError

NewHTTPError constructs a client-safe typed error.

func NotFound

func NotFound(message string) *HTTPError

func PayloadTooLarge

func PayloadTooLarge(message string) *HTTPError

func PreconditionFailed

func PreconditionFailed(message string) *HTTPError

func RateLimited

func RateLimited(message string, retryAfter string) *HTTPError

func Timeout

func Timeout(message string) *HTTPError

func Unauthorized

func Unauthorized(message string) *HTTPError

func Unavailable

func Unavailable(message string) *HTTPError

func UnsupportedMediaType

func UnsupportedMediaType(message string) *HTTPError

func WrapHTTPError

func WrapHTTPError(err error, status int, code, message string) *HTTPError

WrapHTTPError attaches a private cause to a client-safe typed error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) GoString

func (e *HTTPError) GoString() string

func (*HTTPError) Temporary

func (e *HTTPError) Temporary() *HTTPError

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

func (*HTTPError) WithCause

func (e *HTTPError) WithCause(err error) *HTTPError

func (*HTTPError) WithDetails

func (e *HTTPError) WithDetails(details any) *HTTPError

func (*HTTPError) WithHeader

func (e *HTTPError) WithHeader(k, v string) *HTTPError

func (*HTTPError) WithMeta

func (e *HTTPError) WithMeta(k string, v any) *HTTPError

type HTTPPriority

type HTTPPriority struct {
	Urgency     uint8
	Incremental bool
}

HTTPPriority is the RFC 9218 priority of a request or response. Urgency is in the inclusive range 0 (most urgent) through 7 (least urgent).

type Handler

type Handler = HandlerFunc

Handler is the Fiber-compatible name for a request handler.

type HandlerFunc

type HandlerFunc func(Ctx) error

func BudgetMiddleware

func BudgetMiddleware(cfg BudgetConfig) HandlerFunc

BudgetMiddleware creates middleware that attaches a budget to every request.

func ConfigGenerationMiddleware

func ConfigGenerationMiddleware(reloader *ConfigReloader) HandlerFunc

ConfigGenerationMiddleware is middleware that stamps every request with the current configuration generation. This makes it easy to correlate errors with specific configuration versions during deployments.

func DataClass

func DataClass(sensitivity string, categories ...string) HandlerFunc

DataClass marks the current request as handling data of the given sensitivity level (e.g. "confidential", "restricted") and, optionally, one or more data categories (e.g. "pii", "financial", "health"). Both are carried on the request's DataPolicy, which the audit log (AuditEvent. DataClass / AuditEvent.Categories) and compliance report (RouteInfo.Data) read back.

func MerkleAuditMiddleware

func MerkleAuditMiddleware(sink *MerkleAuditSink) HandlerFunc

MerkleAuditMiddleware creates middleware that records audit events with Merkle checkpoint support.

func RequireAuth

func RequireAuth() HandlerFunc

func RequirePermission

func RequirePermission(permissions ...string) HandlerFunc

func RequireRole

func RequireRole(roles ...string) HandlerFunc

func RequireScope

func RequireScope(scopes ...string) HandlerFunc

func RequireValues

func RequireValues(ex Extractor[[]string], code, message, event string, required ...string) HandlerFunc

func RouteSecurity

func RouteSecurity(cfg RouteSecurityConfig) HandlerFunc

RouteSecurity attaches route-local security metadata and enforces common principal/scope/role checks. Register it as route middleware.

func StaticJSON

func StaticJSON(body string) HandlerFunc

StaticJSON returns a handler for immutable application/json responses.

func StaticJSONBytes

func StaticJSONBytes(body []byte) HandlerFunc

StaticJSONBytes returns a handler for immutable pre-encoded JSON bytes.

func StaticText

func StaticText(body string) HandlerFunc

StaticText returns a handler for immutable text/plain responses.

func TenantResolver

func TenantResolver(header string, required bool) HandlerFunc

func TenantResolverWith

func TenantResolverWith(ex Extractor[string], required bool) HandlerFunc

func TypedDelete

func TypedDelete[Res any](fn func(Ctx) (Res, error)) HandlerFunc

TypedDelete creates a type-safe DELETE handler with typed response.

func TypedGet

func TypedGet[Res any](fn func(Ctx) (Res, error)) HandlerFunc

TypedGet creates a type-safe GET handler that doesn't require a request body. The response is automatically serialized to JSON.

func TypedHandler

func TypedHandler[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc

TypedHandler creates a type-safe handler from a function that takes a typed request and returns a typed response. It automatically handles: - Request body parsing (JSON, XML, form data) - Response serialization (JSON) - Content-Type negotiation - Error responses (RFC 9457 Problem Details)

For GET requests with no body, use TypedGet instead.

func TypedPatch

func TypedPatch[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc

TypedPatch creates a type-safe PATCH handler with typed request and response.

func TypedPost

func TypedPost[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc

TypedPost creates a type-safe POST handler with typed request and response.

func TypedPut

func TypedPut[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc

TypedPut creates a type-safe PUT handler with typed request and response.

func TypedStream

func TypedStream[Res any](fn func(Ctx) (Res, io.Reader, error)) HandlerFunc

TypedStream creates a handler that streams a typed response. Useful for large responses that should not be buffered.

func UsePrincipal

func UsePrincipal(ex Extractor[Principal], required ...bool) HandlerFunc

UsePrincipal resolves and stores a Principal for downstream middleware.

func ValidateHeaders

func ValidateHeaders(v any, cfg ...ValidateConfig) HandlerFunc

ValidateHeaders returns a middleware that validates request headers using the provided struct. The struct should have "header" tags for binding.

func ValidateMiddleware

func ValidateMiddleware(factory func() Validator, cfg ...ValidateConfig) HandlerFunc

Validate returns a middleware that validates request body using the provided Validator factory. The factory creates a new validator for each request, which is then decoded into and validated.

Usage:

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required,min=2,max=100"`
    Email string `json:"email" validate:"required,email"`
}

app.Post("/users", validate.Middleware(func() fh.Validator {
    return &CreateUserRequest{}
}), createUserHandler)

func ValidateQuery

func ValidateQuery(v any, cfg ...ValidateConfig) HandlerFunc

ValidateQuery returns a middleware that validates query parameters using the provided struct. The struct should have "query" tags for binding.

type HashChainAuditSink

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

HashChainAuditSink wraps an AuditSink and adds tamper-evident hash-chain metadata to every event. The previous event hash and current event hash are stored in Metadata as audit_prev_hash and audit_hash before forwarding.

func NewHashChainAuditSink

func NewHashChainAuditSink(next AuditSink) *HashChainAuditSink

func (*HashChainAuditSink) Close

func (s *HashChainAuditSink) Close() error

func (*HashChainAuditSink) PreviousHash

func (s *HashChainAuditSink) PreviousHash() string

func (*HashChainAuditSink) WriteAudit

func (s *HashChainAuditSink) WriteAudit(ctx context.Context, e AuditEvent) error
type Header struct {
	Key   []byte
	Value []byte
}

Header is a single HTTP header key/value. Both slices point into the read buffer — zero copy.

type HealthCheckResult

type HealthCheckResult struct {
	Name    string `json:"name"`
	Status  string `json:"status"` // "ok" or "error"
	Latency string `json:"latency,omitempty"`
	Error   string `json:"error,omitempty"`
}

type HealthConfig

type HealthConfig struct {
	Probes map[string]HealthProbe
}

type HealthProbe

type HealthProbe func() bool

type HealthResponse

type HealthResponse struct {
	Status string          `json:"status"`
	Probes map[string]bool `json:"probes,omitempty"`
}

type HookFunc

type HookFunc func() error

HookFunc is a lifecycle hook with optional error propagation.

type Hooks

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

Hooks groups all application lifecycle hooks.

type IdempotencyDecision

type IdempotencyDecision uint8

IdempotencyDecision describes how an idempotency repository resolved a request.

const (
	IdempotencyNew IdempotencyDecision = iota
	IdempotencyReplay
	IdempotencyConflict
	IdempotencyProcessing
)

type IdempotencyJanitor

type IdempotencyJanitor interface {
	PurgeExpired(context.Context, time.Time) (int, error)
}

IdempotencyJanitor is an optional extension for repositories that can purge expired idempotency records. It is useful for long-running services where replay records should not grow without bounds.

type IdempotencyRecord

type IdempotencyRecord struct {
	Key         string              `json:"key"`
	RequestHash string              `json:"request_hash"`
	Method      string              `json:"method,omitempty"`
	Path        string              `json:"path,omitempty"`
	State       string              `json:"state"`
	StatusCode  int                 `json:"status_code,omitempty"`
	ContentType string              `json:"content_type,omitempty"`
	Headers     map[string][]string `json:"headers,omitempty"`
	Response    []byte              `json:"response,omitempty"`
	CreatedAt   time.Time           `json:"created_at"`
	UpdatedAt   time.Time           `json:"updated_at"`
	ExpiresAt   time.Time           `json:"expires_at"`
}

type IdempotencyRepository

type IdempotencyRepository interface {
	Begin(key, reqHash, method, path string) (IdempotencyDecision, *IdempotencyRecord, error)
	Complete(key, reqHash string, status int, contentType string, headers map[string][]string, response []byte) error
	Close() error
}

IdempotencyRepository stores request hashes and completed response snapshots. Implementations must make Begin atomic for a given key.

type IdempotencyStore

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

func OpenIdempotencyStore

func OpenIdempotencyStore(path string, ttl time.Duration) (*IdempotencyStore, error)

func (*IdempotencyStore) Begin

func (s *IdempotencyStore) Begin(key, reqHash, method, path string) (IdempotencyDecision, *IdempotencyRecord, error)

func (*IdempotencyStore) Close

func (s *IdempotencyStore) Close() error

func (*IdempotencyStore) Complete

func (s *IdempotencyStore) Complete(key, reqHash string, status int, contentType string, headers map[string][]string, response []byte) error

func (*IdempotencyStore) Path

func (s *IdempotencyStore) Path() string

func (*IdempotencyStore) PurgeExpired

func (s *IdempotencyStore) PurgeExpired(ctx context.Context, now time.Time) (int, error)

type Inbox

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

func (*Inbox) Accept

func (i *Inbox) Accept(ctx context.Context, ev InboxEvent, queueType string) (string, error)

type InboxEvent

type InboxEvent struct {
	ID, Source, EventID string
	Payload             json.RawMessage
	Headers             map[string]string
	CreatedAt           time.Time
}

type InboxMessage

type InboxMessage struct {
	ID        string    `json:"id"`
	Source    string    `json:"source,omitempty"`
	Hash      string    `json:"hash,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

type InboxStore

type InboxStore interface {
	BeginInbox(context.Context, InboxMessage) (bool, error)
	Close() error
}

type JSONAppendFunc

type JSONAppendFunc func([]byte) ([]byte, error)

JSONAppendFunc adapts a function to JSONAppender. It lets hot handlers build dynamic JSON directly into fh's pooled response buffer without string concatenation or encoding/json reflection.

func (JSONAppendFunc) AppendJSON

func (f JSONAppendFunc) AppendJSON(dst []byte) ([]byte, error)

type JSONAppender

type JSONAppender interface {
	AppendJSON(dst []byte) ([]byte, error)
}

JSONAppender is an optional zero/low-allocation hot path for DTOs generated by a json code generator or written by hand. If a value implements this interface, jsonCodec.Marshal uses it before the configured JSON engine.

type JSONDecoder

type JSONDecoder interface {
	Decode(v any) error
}

JSONDecoder is the decoder surface required by the codec registry.

func NewJSONDecoder

func NewJSONDecoder(r io.Reader) JSONDecoder

NewJSONDecoder creates a decoder from the active JSON engine.

type JSONDecoderConfigurer

type JSONDecoderConfigurer interface {
	UseNumber()
	DisallowUnknownFields()
}

JSONDecoderConfigurer is optional. Engines should implement it when they support standard decoder configuration.

type JSONEncoder

type JSONEncoder interface {
	Encode(v any) error
}

JSONEncoder is the small encoder surface required by the codec registry. It is intentionally compatible with encoding/json.Encoder and with engines such as sonic, go-json, jsoniter, or your own JSON adapter.

func NewJSONEncoder

func NewJSONEncoder(w io.Writer) JSONEncoder

NewJSONEncoder creates an encoder from the active JSON engine.

type JSONEncoderConfigurer

type JSONEncoderConfigurer interface {
	SetIndent(prefix, indent string)
	SetEscapeHTML(on bool)
}

JSONEncoderConfigurer is optional. Engines should implement it when they support standard encoder configuration.

type JSONEngine

type JSONEngine interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
	NewEncoder(w io.Writer) JSONEncoder
	NewDecoder(r io.Reader) JSONDecoder
	Valid(data []byte) bool
}

JSONEngine is the full pluggable JSON backend used by jsonCodec and ndjsonCodec. The default implementation is encoding/json for maximum compatibility. Replace it during process startup with SetJSONEngine to use a high-throughput standalone engine.

func CurrentJSONEngine

func CurrentJSONEngine() JSONEngine

CurrentJSONEngine returns the active JSON backend.

type JSONEngineFuncSet

type JSONEngineFuncSet struct {
	MarshalFunc    func(any) ([]byte, error)
	UnmarshalFunc  func([]byte, any) error
	NewEncoderFunc func(io.Writer) JSONEncoder
	NewDecoderFunc func(io.Reader) JSONDecoder
	ValidFunc      func([]byte) bool
}

JSONEngineFuncSet adapts function values into JSONEngine. This is useful for engines that expose Marshal/Unmarshal functions but no concrete codec type.

func (JSONEngineFuncSet) Marshal

func (e JSONEngineFuncSet) Marshal(v any) ([]byte, error)

func (JSONEngineFuncSet) NewDecoder

func (e JSONEngineFuncSet) NewDecoder(r io.Reader) JSONDecoder

func (JSONEngineFuncSet) NewEncoder

func (e JSONEngineFuncSet) NewEncoder(w io.Writer) JSONEncoder

func (JSONEngineFuncSet) Unmarshal

func (e JSONEngineFuncSet) Unmarshal(data []byte, v any) error

func (JSONEngineFuncSet) Valid

func (e JSONEngineFuncSet) Valid(data []byte) bool

type JSONField

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

type JSONMarshaler

type JSONMarshaler interface {
	MarshalJSON() ([]byte, error)
}

JSONMarshaler is compatible with encoding/json.Marshaler and high-performance JSON engines that honor MarshalJSON.

type JSONRawMessage

type JSONRawMessage []byte

JSONRawMessage is a stdlib-independent raw JSON payload type for codec callers that do not want to depend on encoding/json.RawMessage.

type JSONSchema

type JSONSchema map[string]any

type JSONStreamingDecoder

type JSONStreamingDecoder interface {
	JSONDecoder
	More() bool
	Token() (any, error)
	Buffered() io.Reader
	InputOffset() int64
}

JSONStreamingDecoder is optional and mirrors extra encoding/json.Decoder APIs.

type JSONUnmarshaler

type JSONUnmarshaler interface {
	UnmarshalJSON([]byte) error
}

JSONUnmarshaler is compatible with encoding/json.Unmarshaler and high-performance JSON engines that honor UnmarshalJSON.

type JSONValue

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

func (JSONValue) AppendJSON

func (f JSONValue) AppendJSON(dst []byte) ([]byte, error)

type KernelBackend

type KernelBackend = kernel.KernelBackend

type KernelCapabilities

type KernelCapabilities = kernel.KernelCapabilities

func ProbeKernel

func ProbeKernel() KernelCapabilities

type KernelConfig

type KernelConfig = kernel.KernelConfig

func DefaultKernelConfig

func DefaultKernelConfig() KernelConfig

func HighPerformanceKernelConfig

func HighPerformanceKernelConfig() KernelConfig

func ProductionKernelConfig

func ProductionKernelConfig() KernelConfig

type KernelProfile

type KernelProfile = kernel.KernelProfile

type KernelReadinessIssue

type KernelReadinessIssue = kernel.ReadinessIssue

type KernelReadinessReport

type KernelReadinessReport = kernel.ReadinessReport

type KernelReadinessSeverity

type KernelReadinessSeverity = kernel.ReadinessSeverity

type KernelRuntimeInfo

type KernelRuntimeInfo = kernel.KernelRuntimeInfo

type LedgerEntry

type LedgerEntry struct {
	ID, TenantID, ActorID, Action, Resource, ResourceID, Decision, BeforeHash, AfterHash, RequestID string
	CreatedAt                                                                                       time.Time
}

Ledger records a business operation with before/after hashes for compliance evidence.

type LifecycleState

type LifecycleState string

Lifecycle state and compensation.

const (
	LifecycleReceived    LifecycleState = "received"
	LifecycleValidated   LifecycleState = "validated"
	LifecycleAuthorized  LifecycleState = "authorized"
	LifecycleAccepted    LifecycleState = "accepted"
	LifecycleQueued      LifecycleState = "queued"
	LifecycleProcessing  LifecycleState = "processing"
	LifecycleCompleted   LifecycleState = "completed"
	LifecycleFailed      LifecycleState = "failed"
	LifecycleCompensated LifecycleState = "compensated"
)

type LogAdapter

type LogAdapter struct {
	Logger *log.Logger
}

LogAdapter wraps a standard library *log.Logger to satisfy the Logger interface. Use it when migrating from std log to the fh.Logger interface without changing existing logger setup.

func (*LogAdapter) Debug

func (a *LogAdapter) Debug(msg string, args ...any)

func (*LogAdapter) Error

func (a *LogAdapter) Error(msg string, args ...any)

func (*LogAdapter) Info

func (a *LogAdapter) Info(msg string, args ...any)

func (*LogAdapter) Printf

func (a *LogAdapter) Printf(format string, args ...any)

func (*LogAdapter) Warn

func (a *LogAdapter) Warn(msg string, args ...any)

type Logger

type Logger interface {
	Printf(format string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
	Debug(msg string, args ...any)
}

Logger is the interface for application-level logging in fh. It supports both printf-style (Printf) and structured leveled logging (Info, Warn, Error, Debug) with key-value pair arguments, following the same convention as log/slog.

Implementations can adapt any third-party logger by wrapping it.

func NewDefaultLogger

func NewDefaultLogger() Logger

NewDefaultLogger returns the default fh Logger backed by log/slog. It writes text-formatted output to stderr at debug level and above.

func NewNoopLogger

func NewNoopLogger() Logger

NewNoopLogger returns a Logger that silently discards all log messages.

It is useful for benchmarks, tests, embedded applications, or deployments where fh logging is handled elsewhere.

type MaintenanceReport

type MaintenanceReport struct {
	Queue     QueueStats `json:"queue"`
	Compacted bool       `json:"compacted"`
}

Maintenance.

type Map

type Map map[string]any

type MemoryHTTPCache

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

MemoryHTTPCache is a compact in-memory HTTP cache suitable for service clients and tests.

func NewMemoryHTTPCache

func NewMemoryHTTPCache(ttl time.Duration, maxBody int64) *MemoryHTTPCache

type MemoryOutboxInboxStore

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

func NewMemoryOutboxInboxStore

func NewMemoryOutboxInboxStore() *MemoryOutboxInboxStore

func NewMemoryOutboxInboxStoreWithLimit

func NewMemoryOutboxInboxStoreWithLimit(maxOutbox, maxInbox int) *MemoryOutboxInboxStore

func (*MemoryOutboxInboxStore) BeginInbox

func (s *MemoryOutboxInboxStore) BeginInbox(ctx context.Context, m InboxMessage) (bool, error)

func (*MemoryOutboxInboxStore) ClaimOutbox

func (s *MemoryOutboxInboxStore) ClaimOutbox(ctx context.Context, now time.Time, limit int) ([]*OutboxMessage, error)

func (*MemoryOutboxInboxStore) Close

func (s *MemoryOutboxInboxStore) Close() error

func (*MemoryOutboxInboxStore) CompleteOutbox

func (s *MemoryOutboxInboxStore) CompleteOutbox(ctx context.Context, id string) error

func (*MemoryOutboxInboxStore) FailOutbox

func (s *MemoryOutboxInboxStore) FailOutbox(ctx context.Context, id string, err error) error

func (*MemoryOutboxInboxStore) ListOutbox

func (s *MemoryOutboxInboxStore) ListOutbox(ctx context.Context, state string, limit int) ([]OutboxMessage, error)

func (*MemoryOutboxInboxStore) RetryOutbox

func (s *MemoryOutboxInboxStore) RetryOutbox(ctx context.Context, id string, err error, delay time.Duration) error

func (*MemoryOutboxInboxStore) SaveOutbox

func (s *MemoryOutboxInboxStore) SaveOutbox(ctx context.Context, m *OutboxMessage) error

type MerkleAuditSink

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

MerkleAuditSink wraps an AuditSink and periodically creates Merkle checkpoints from batches of audit events. Each checkpoint combines the events into a Merkle tree and publishes the root hash, making deletion or modification of historical audit events detectable.

func NewMerkleAuditSink

func NewMerkleAuditSink(cfg MerkleConfig) *MerkleAuditSink

NewMerkleAuditSink creates a Merkle checkpoint audit sink.

func (*MerkleAuditSink) Close

func (s *MerkleAuditSink) Close() error

Close stops the flush loop and creates a final checkpoint if needed.

func (*MerkleAuditSink) WriteAudit

func (s *MerkleAuditSink) WriteAudit(ctx context.Context, e AuditEvent) error

WriteAudit records an event and adds it to the current Merkle bucket.

type MerkleCheckpoint

type MerkleCheckpoint struct {
	// Sequence is the checkpoint sequence number.
	Sequence uint64 `json:"sequence"`

	// RootHash is the Merkle root of all events in this checkpoint.
	RootHash string `json:"root_hash"`

	// EventCount is the number of events in this checkpoint.
	EventCount int `json:"event_count"`

	// PrevCheckpointHash is the hash of the previous checkpoint for chaining.
	PrevCheckpointHash string `json:"prev_checkpoint_hash"`

	// StartTime is the time the first event in this checkpoint was received.
	StartTime time.Time `json:"start_time"`

	// EndTime is the time the last event in this checkpoint was received.
	EndTime time.Time `json:"end_time"`

	// ServerID identifies the server that created this checkpoint.
	ServerID string `json:"server_id"`

	// Signature is an optional HMAC signature of the checkpoint.
	Signature string `json:"signature,omitempty"`
}

MerkleCheckpoint represents a batch of audit events combined into a Merkle root.

type MerkleConfig

type MerkleConfig struct {
	// BucketSize is the number of events per checkpoint. Default: 100.
	BucketSize int

	// CheckpointInterval is the maximum time between checkpoints. Default: 5 minutes.
	CheckpointInterval time.Duration

	// ServerID identifies this server in checkpoints.
	ServerID string

	// OnCheckpoint is called when a new checkpoint is created.
	OnCheckpoint func(MerkleCheckpoint)

	// Sink is the underlying audit sink to write events to.
	Sink AuditSink
}

MerkleConfig configures the Merkle audit checkpoint system.

type Meta

type Meta struct {
	Page       int    `json:"page,omitempty"`
	PerPage    int    `json:"per_page,omitempty"`
	Total      int64  `json:"total,omitempty"`
	TotalPages int    `json:"total_pages,omitempty"`
	RequestID  string `json:"request_id,omitempty"`
}

Meta holds response metadata for pagination, caching, etc.

type MethodNotAllowedHandler

type MethodNotAllowedHandler func(Ctx, []string) error

MethodNotAllowedHandler handles requests whose path matches one or more routes but whose method is not allowed. allowed is already ordered for the Allow header.

type Mode

type Mode string

Mode controls framework safety defaults and config validation severity.

const (
	// ModeFast keeps raw throughput defaults for trusted benchmark/edge use.
	ModeFast        Mode = "fast"
	ModeDevelopment Mode = "development"
	ModeProduction  Mode = "production"
	// ModeEnterprise enables strict protocol, audit/reliability and compliance evidence defaults.
	ModeEnterprise Mode = "enterprise"
	ModeStrict     Mode = "strict"
)

type MultipartBinder

type MultipartBinder interface {
	BindMultipart(*MultipartForm) error
}

MultipartBinder allows applications to bind multipart data into structs without reflection.

type MultipartFile

type MultipartFile struct {
	FieldName string
	FileName  string
	Header    textproto.MIMEHeader
	Size      int64
	Data      []byte
}

MultipartFile is an in-memory uploaded file. Body parsers should enforce request-body limits before calling codecs.

func (MultipartFile) Open

func (f MultipartFile) Open() io.ReadCloser

Open returns a new reader over the uploaded file contents.

func (MultipartFile) Save

func (f MultipartFile) Save(dst string) error

Save writes an uploaded file to dst with restrictive default permissions.

type MultipartForm

type MultipartForm struct {
	Values url.Values
	Files  map[string][]MultipartFile
}

MultipartForm is the decoded representation of multipart/form-data.

func (*MultipartForm) File

func (m *MultipartForm) File(field string) (*MultipartFile, error)

File returns the first uploaded file for a field.

func (*MultipartForm) FileValues

func (m *MultipartForm) FileValues(field string) []MultipartFile

FileValues returns all uploaded files for a field.

func (*MultipartForm) First

func (m *MultipartForm) First(key string) string

First returns the first field value for key, or empty string.

type NopClientMetrics

type NopClientMetrics struct{}

func (NopClientMetrics) Error

func (NopClientMetrics) Inflight

func (NopClientMetrics) Inflight(int64)

func (NopClientMetrics) Observe

type NotFoundHandler

type NotFoundHandler func(Ctx) error

NotFoundHandler handles requests that do not match any route.

type OCSPStapler

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

OCSPStapler fetches and caches OCSP responses for a certificate chain.

func NewOCSPStapler

func NewOCSPStapler(certFile, keyFile, caFile string) (*OCSPStapler, error)

NewOCSPStapler creates a stapler. caFile should point to the issuing CA's PEM. The leaf cert is loaded from certFile.

func (*OCSPStapler) Staple

func (s *OCSPStapler) Staple() []byte

Staple returns the cached OCSP response, or nil if not available.

func (*OCSPStapler) Stop

func (s *OCSPStapler) Stop()

Stop halts the background refresh goroutine and waits for it to exit.

type OpenAPIConfig

type OpenAPIConfig struct {
	Title, Version, Description string
	Servers                     []string
}

OpenAPIConfig controls native OpenAPI export and docs UI.

type Option

type Option func(*Config)

Option is a functional option for configuring an App via New.

func WithAllowedHosts

func WithAllowedHosts(hosts ...string) Option

func WithBaseContext

func WithBaseContext(fn func(net.Listener) context.Context) Option

func WithCaptureResponseBody

func WithCaptureResponseBody(enabled bool) Option

func WithCompliance

func WithCompliance(cc ComplianceConfig) Option

func WithComplianceEndpointAuth

func WithComplianceEndpointAuth(middleware ...HandlerFunc) Option

WithComplianceEndpointAuth sets (without disturbing any other Compliance field already set by an earlier option, e.g. NewEnterprise's defaults) the auth middleware guarding the /_fh/* compliance/health/runtime introspection endpoints mounted when Compliance.ExposeEndpoints is true. Apply this after NewEnterprise/NewProduction, or ExposeEndpoints mounts those routes with no authentication.

func WithConnContext

func WithConnContext(fn func(context.Context, net.Conn) context.Context) Option

func WithContentSecurityPolicy

func WithContentSecurityPolicy(policy string) Option

func WithDebug

func WithDebug(enabled bool) Option

func WithDisableH2C

func WithDisableH2C(disabled bool) Option

func WithDisableHTTP2

func WithDisableHTTP2(disabled bool) Option

func WithDisableKeepAlive

func WithDisableKeepAlive(disabled bool) Option

func WithDisablePanicRecovery

func WithDisablePanicRecovery(disabled bool) Option

func WithEnvironment

func WithEnvironment(env Environment) Option

func WithErrorHandler

func WithErrorHandler(h ErrorHandler) Option

func WithErrorOptions

func WithErrorOptions(eo ErrorOptions) Option

func WithHTTP2IdleTimeout

func WithHTTP2IdleTimeout(d time.Duration) Option

func WithHandlerTimeout

func WithHandlerTimeout(d time.Duration) Option

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) Option

func WithKernel

func WithKernel(cfg KernelConfig) Option

func WithKernelDefaults

func WithKernelDefaults() Option

func WithLogger

func WithLogger(l Logger) Option

func WithMaxConcurrentStreams

func WithMaxConcurrentStreams(n uint32) Option

func WithMaxConnections

func WithMaxConnections(n int) Option

func WithMaxConnectionsPerIP

func WithMaxConnectionsPerIP(n int) Option

func WithMaxGoroutines

func WithMaxGoroutines(n int) Option

func WithMaxHeaderCount

func WithMaxHeaderCount(n int) Option

func WithMaxHeaderListSize

func WithMaxHeaderListSize(n int) Option

func WithMaxHeapBytes

func WithMaxHeapBytes(n uint64) Option

func WithMaxInFlightRequests

func WithMaxInFlightRequests(n int64) Option

func WithMaxRequestBodySize

func WithMaxRequestBodySize(n int) Option

func WithMaxRequestLineSize

func WithMaxRequestLineSize(n int) Option

func WithMethodNotAllowedHandler

func WithMethodNotAllowedHandler(h MethodNotAllowedHandler) Option

func WithMode

func WithMode(mode Mode) Option

WithMode selects the runtime profile. ModeFast keeps benchmark-oriented defaults; ModeProduction and ModeStrict enable safer network defaults.

func WithNotFoundHandler

func WithNotFoundHandler(h NotFoundHandler) Option

func WithOptionsHandler

func WithOptionsHandler(h OptionsHandler) Option

func WithReadBufferSize

func WithReadBufferSize(n int) Option

func WithReadHeaderTimeout

func WithReadHeaderTimeout(d time.Duration) Option

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

func WithReliability

func WithReliability(r ReliabilityConfig) Option

func WithRequestBodyTimeout

func WithRequestBodyTimeout(d time.Duration) Option

func WithRequestHeadHandler

func WithRequestHeadHandler(h HandlerFunc) Option

func WithResourceCheckInterval

func WithResourceCheckInterval(d time.Duration) Option

func WithSafeParams

func WithSafeParams(enabled bool) Option

func WithSecureByDefault

func WithSecureByDefault(enabled bool) Option

WithSecureByDefault enables the fail-closed framework security baseline. It is equivalent to setting Config.SecureByDefault.

This bounds protocol input (buffer/connection/body-size limits) and hardens response headers (HSTS, COOP/CORP, Referrer-Policy, ...). It does NOT add authentication, authorization, CSRF protection, rate limiting, or a Host allow-list — see Config.SecureByDefault and NewProduction for the full scope, and mount mw/basicauth/mw/apikey/mw/session (or another principal extractor), mw/csrf, mw/ratelimiter, and WithAllowedHosts explicitly for those.

func WithSendDateHeader

func WithSendDateHeader(enabled bool) Option

func WithSendKeepAliveHeader

func WithSendKeepAliveHeader(enabled bool) Option

func WithServerHeader

func WithServerHeader(header string) Option

func WithSharedState

func WithSharedState(provider SharedStateProvider) Option

WithSharedState configures the application-level shared-state provider. The App assumes lifecycle ownership and closes provider during graceful shutdown. Resolve isolated stores with App.StateStore or App.MustStateStore.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

func WithStartupBanner

func WithStartupBanner(cfg StartupBannerConfig) Option

WithStartupBanner replaces the whole startup banner configuration.

func WithStartupBannerColor

func WithStartupBannerColor(enabled bool) Option

WithStartupBannerColor enables/disables ANSI color in the startup banner.

func WithStartupBannerDisabled

func WithStartupBannerDisabled(disabled bool) Option

WithStartupBannerDisabled enables/disables the startup banner. Passing true disables it.

func WithStartupBannerName

func WithStartupBannerName(name string) Option

WithStartupBannerName sets the displayed application/framework name.

func WithStartupBannerOutput

func WithStartupBannerOutput(w io.Writer) Option

WithStartupBannerOutput sets the destination for the startup banner.

func WithStartupBannerSubtitle

func WithStartupBannerSubtitle(subtitle string) Option

WithStartupBannerSubtitle sets the displayed subtitle.

func WithStartupBannerVersion

func WithStartupBannerVersion(version string) Option

WithStartupBannerVersion sets the displayed version string.

func WithStreamRequestBody

func WithStreamRequestBody(enabled bool) Option

func WithTLSHandshakeTimeout

func WithTLSHandshakeTimeout(d time.Duration) Option

func WithTemplateEngine

func WithTemplateEngine(te TemplateEngine) Option

func WithWriteBufferSize

func WithWriteBufferSize(n int) Option

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

type OptionsHandler

type OptionsHandler func(Ctx, []string) error

OptionsHandler handles automatic OPTIONS responses for matched routes and server-wide OPTIONS * requests. allowed is already ordered for the Allow header.

type Outbox

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

func (*Outbox) Publish

func (o *Outbox) Publish(ctx context.Context, ev OutboxEvent) (string, error)

type OutboxConfig

type OutboxConfig struct {
	Store       OutboxStore
	Dispatcher  OutboxDispatcher
	MaxAttempts int
	Backoff     time.Duration
}

type OutboxDispatcher

type OutboxDispatcher func(context.Context, *OutboxMessage) error

type OutboxEvent

type OutboxEvent struct {
	ID, Topic, Key string
	Payload        json.RawMessage
	Headers        map[string]string
	CreatedAt      time.Time
}

type OutboxMessage

type OutboxMessage struct {
	ID          string            `json:"id"`
	Topic       string            `json:"topic"`
	Payload     json.RawMessage   `json:"payload,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
	State       string            `json:"state"`
	Attempts    int               `json:"attempts"`
	MaxAttempts int               `json:"max_attempts"`
	NextAttempt time.Time         `json:"next_attempt,omitempty"`
	LastError   string            `json:"last_error,omitempty"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
}

type OutboxStore

type OutboxStore interface {
	SaveOutbox(context.Context, *OutboxMessage) error
	ClaimOutbox(context.Context, time.Time, int) ([]*OutboxMessage, error)
	CompleteOutbox(context.Context, string) error
	RetryOutbox(context.Context, string, error, time.Duration) error
	FailOutbox(context.Context, string, error) error
	ListOutbox(context.Context, string, int) ([]OutboxMessage, error)
	Close() error
}

type PanicError

type PanicError struct {
	Value any
	Stack []byte
}

PanicError wraps a recovered panic. Stack is intentionally not returned to clients unless debug exposure is enabled.

func NewPanicError

func NewPanicError(value any) *PanicError

func (*PanicError) Error

func (e *PanicError) Error() string

type Param

type Param struct {
	Key   string
	Value string
}

type PreforkConfig

type PreforkConfig struct {
	// Workers is the number of OS worker processes to run. Defaults to
	// runtime.NumCPU() — parallelism comes from separate processes bound to
	// the same port via SO_REUSEPORT, not from goroutine scheduling alone.
	Workers int
	// WorkerReactors overrides each worker's kernel.Reactors (the existing
	// goroutine-level SO_REUSEPORT accept sharding within one process).
	// Defaults to 1: with Workers OS processes already providing parallelism,
	// stacking reactors on top by default would oversubscribe the machine.
	WorkerReactors int
	// ReadyTimeout bounds how long the master waits for a worker to report a
	// bound, accepting listener before treating startup (or a rollout) as
	// failed.
	ReadyTimeout time.Duration
	// ShutdownTimeout bounds how long a worker gets to drain in-flight
	// requests before the master force-kills it, both during a rolling
	// restart and final shutdown.
	ShutdownTimeout time.Duration
	// RestartBackoffMin/Max bound the exponential backoff applied when
	// respawning a worker that exits unexpectedly, to avoid crash-looping a
	// broken binary.
	RestartBackoffMin time.Duration
	RestartBackoffMax time.Duration
}

PreforkConfig configures App.ListenPrefork's OS-process supervisor. Zero values are replaced with sane defaults by normalize.

type PreforkOption

type PreforkOption func(*PreforkConfig)

PreforkOption configures a PreforkConfig passed to App.ListenPrefork.

func WithPreforkReadyTimeout

func WithPreforkReadyTimeout(d time.Duration) PreforkOption

func WithPreforkRestartBackoff

func WithPreforkRestartBackoff(min, max time.Duration) PreforkOption

func WithPreforkShutdownTimeout

func WithPreforkShutdownTimeout(d time.Duration) PreforkOption

func WithPreforkWorkerReactors

func WithPreforkWorkerReactors(n int) PreforkOption

func WithPreforkWorkers

func WithPreforkWorkers(n int) PreforkOption

type Principal

type Principal struct {
	ID          string         `json:"id"`
	Type        string         `json:"type,omitempty"`
	TenantID    string         `json:"tenant_id,omitempty"`
	Subject     string         `json:"subject,omitempty"`
	Roles       []string       `json:"roles,omitempty"`
	Scopes      []string       `json:"scopes,omitempty"`
	Permissions []string       `json:"permissions,omitempty"`
	Claims      map[string]any `json:"claims,omitempty"`
	AuthMethod  string         `json:"auth_method,omitempty"`
}

func ExtractPrincipal

func ExtractPrincipal(c Ctx, ex PrincipalExtractors) (Principal, bool, error)

ExtractPrincipal builds a Principal from the configured field extractors.

func PrincipalFrom

func PrincipalFrom(c Ctx) (Principal, bool)

type PrincipalExtractors

type PrincipalExtractors struct {
	ID          Extractor[string]
	Type        Extractor[string]
	TenantID    Extractor[string]
	Subject     Extractor[string]
	Roles       Extractor[[]string]
	Scopes      Extractor[[]string]
	Permissions Extractor[[]string]
	Claims      Extractor[map[string]any]
	AuthMethod  Extractor[string]
}

PrincipalExtractors resolves the standard Principal fields without assuming where they are stored. Empty extractors are skipped.

type Problem

type Problem struct {
	Type       string         `json:"type,omitempty"`
	Title      string         `json:"title,omitempty"`
	Status     int            `json:"status,omitempty"`
	Detail     string         `json:"detail,omitempty"`
	Instance   string         `json:"instance,omitempty"`
	Code       string         `json:"code,omitempty"`
	Extensions map[string]any `json:"-"`
}

Problem is an RFC 9457 Problem Details document. Extensions are emitted as top-level members.

func (Problem) MarshalJSON

func (p Problem) MarshalJSON() ([]byte, error)

type ProblemDetailsPayload

type ProblemDetailsPayload struct {
	Type     string         `json:"type,omitempty"`
	Title    string         `json:"title"`
	Status   int            `json:"status"`
	Detail   string         `json:"detail,omitempty"`
	Instance string         `json:"instance,omitempty"`
	Extra    map[string]any `json:"extra,omitempty"`
}

ProblemDetailsPayload represents an RFC 9457 / RFC 7807 problem details object.

type ProxyProtocolConfig

type ProxyProtocolConfig struct {
	// Timeout is the maximum time to wait for the PROXY header.
	// Defaults to 5 seconds.
	Timeout time.Duration

	// FallbackPassthrough allows connections without a PROXY header to be served as normal.
	// Defaults to false (strict mode).
	FallbackPassthrough bool

	// TrustedPeers restricts which direct TCP peers are allowed to send a PROXY
	// header. A connection whose raw TCP source address does not fall within one
	// of these networks has its PROXY header rejected, preventing arbitrary
	// clients from spoofing their source IP (which downstream code trusts for
	// audit logs, rate limiting, and IP-based blocking).
	//
	// If empty and TrustAll is false, no peer is trusted and every PROXY header
	// is rejected (connections are only accepted if FallbackPassthrough is set).
	TrustedPeers []*net.IPNet

	// TrustAll accepts a PROXY header from any direct peer, including the
	// public internet. Only use this when the listener is genuinely
	// unreachable except through a trusted load balancer/proxy.
	TrustAll bool
}

ProxyProtocolConfig configures PROXY protocol negotiation.

type ProxyProtocolListener

type ProxyProtocolListener struct {
	net.Listener
	// contains filtered or unexported fields
}

ProxyProtocolListener wraps an underlying net.Listener and decodes PROXY headers on accept.

func NewProxyProtocolListener

func NewProxyProtocolListener(ln net.Listener, cfg ...ProxyProtocolConfig) *ProxyProtocolListener

NewProxyProtocolListener wraps ln with PROXY protocol v1 and v2 support.

func (*ProxyProtocolListener) Accept

func (l *ProxyProtocolListener) Accept() (net.Conn, error)

Accept waits for and returns the next connection to the listener, parsing its PROXY header.

type PushPromise

type PushPromise struct {
	Method  string
	Path    string
	Headers map[string]string
}

PushPromise represents an HTTP/2 Server Push promise.

type Queue

type Queue interface {
	Register(jobType string, handler QueueHandler)
	Enqueue(jobType string, payload any, headers ...map[string]string) (string, error)
	Start() error
	Close() error
	Stats() (QueueStats, error)
}

Queue is the application-facing async job queue contract.

type QueueEvent

type QueueEvent struct {
	ID        string    `json:"id"`
	JobID     string    `json:"job_id"`
	Type      string    `json:"type"`
	State     string    `json:"state"`
	Event     string    `json:"event"`
	Attempts  int       `json:"attempts"`
	Error     string    `json:"error,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

type QueueFailedOperator

type QueueFailedOperator interface {
	RequeueFailed(context.Context, string) error
	DiscardFailed(context.Context, string) error
}

QueueFailedOperator is an optional extension for QueueStorage implementations that can safely move failed jobs back to pending or discard them from the DLQ.

type QueueHandler

type QueueHandler func(context.Context, *QueueJob) error

type QueueJanitor

type QueueJanitor interface {
	PurgeJobs(context.Context, string, time.Time, int) (int, error)
}

QueueJanitor is an optional extension for QueueStorage implementations that can purge old terminal jobs. State should normally be done or failed. Before controls the UpdatedAt cutoff. Limit <= 0 lets implementations choose a safe default.

type QueueJob

type QueueJob struct {
	ID             string            `json:"id"`
	Type           string            `json:"type"`
	Payload        json.RawMessage   `json:"payload,omitempty"`
	Headers        map[string]string `json:"headers,omitempty"`
	Attempts       int               `json:"attempts"`
	MaxAttempts    int               `json:"max_attempts"`
	VisibleAt      time.Time         `json:"visible_at"`
	CreatedAt      time.Time         `json:"created_at"`
	UpdatedAt      time.Time         `json:"updated_at"`
	LastError      string            `json:"last_error,omitempty"`
	Priority       int               `json:"priority,omitempty"`
	RunAt          time.Time         `json:"run_at,omitempty"`
	ConcurrencyKey string            `json:"concurrency_key,omitempty"`
}

type QueueJobLister

type QueueJobLister interface {
	ListJobs(context.Context, string, int) ([]QueueJobSnapshot, error)
}

QueueJobLister is an optional extension for QueueStorage implementations that can expose jobs for admin/API tooling. The state value should be one of pending, processing, done or failed; an empty state means all states. Limit <= 0 lets the implementation choose a safe default.

type QueueJobSnapshot

type QueueJobSnapshot struct {
	ID             string            `json:"id"`
	Type           string            `json:"type"`
	State          string            `json:"state"`
	Headers        map[string]string `json:"headers,omitempty"`
	Attempts       int               `json:"attempts"`
	MaxAttempts    int               `json:"max_attempts"`
	VisibleAt      time.Time         `json:"visible_at"`
	CreatedAt      time.Time         `json:"created_at"`
	UpdatedAt      time.Time         `json:"updated_at"`
	LastError      string            `json:"last_error,omitempty"`
	Priority       int               `json:"priority,omitempty"`
	RunAt          time.Time         `json:"run_at,omitempty"`
	ConcurrencyKey string            `json:"concurrency_key,omitempty"`
	PayloadBytes   int               `json:"payload_bytes"`
	PayloadPreview string            `json:"payload_preview,omitempty"`
}

QueueJobSnapshot is a redacted, admin-safe view of a durable queue job. It is intentionally metadata-first; payload previews are bounded to avoid leaking or returning very large bodies from ops endpoints.

type QueueStats

type QueueStats struct{ Pending, Processing, Done, Failed int }

type QueueStorage

type QueueStorage interface {
	Enqueue(context.Context, *QueueJob) error
	Claim(context.Context, time.Time) (*QueueJob, error)
	Complete(context.Context, *QueueJob) error
	Retry(context.Context, *QueueJob, error, time.Duration) error
	Fail(context.Context, *QueueJob, error) error
	Recover(context.Context) error
	Stats(context.Context) (QueueStats, error)
	Close() error
}

QueueStorage is the persistence contract used by DurableQueue. A DBMS backend should implement Claim atomically, for example using SELECT ... FOR UPDATE SKIP LOCKED or an UPDATE ... RETURNING lease pattern.

type REFEngine added in v0.0.26

type REFEngine interface {
	// Capabilities returns the capability registry.
	Capabilities() any

	// Intents returns the intent registry.
	Intents() any

	// RegisterDefinition registers a type-erased intent.
	RegisterDefinition(def any) error

	// Compile builds execution plans for all registered intents.
	Compile() error

	// Dispatch executes an intent by invocation input.
	Dispatch(ctx context.Context, inv any) (any, error)

	// DispatchPreview evaluates an intent without committing effects.
	DispatchPreview(ctx context.Context, inv any) (any, error)

	// Plan returns the compiled execution plan for an intent name.
	Plan(name string) (any, bool)
}

REFEngine defines the interface for the Runtime Execution Fabric engine. Applications can inject their concrete *ref.Engine implementation here to decouple the fh framework from the ref package.

type RedactionConfig

type RedactionConfig struct {
	Enabled     bool          `json:"enabled"`
	Fields      []string      `json:"fields,omitempty"`
	Replacement string        `json:"replacement,omitempty"`
	Mode        RedactionMode `json:"mode,omitempty"`
}

func DefaultRedactionConfig

func DefaultRedactionConfig() RedactionConfig

type RedactionMode

type RedactionMode string
const (
	RedactReplace RedactionMode = "replace"
	RedactPartial RedactionMode = "partial"
)

type Redactor

type Redactor struct {
	Keys        []string
	Replacement string
}

func DefaultRedactor

func DefaultRedactor() *Redactor

func NewRedactor

func NewRedactor(cfg RedactionConfig) *Redactor

func (*Redactor) RedactHeaders

func (r *Redactor) RedactHeaders(in map[string][]string) map[string][]string

func (*Redactor) RedactMap

func (r *Redactor) RedactMap(in map[string]any) map[string]any

func (*Redactor) RedactString

func (r *Redactor) RedactString(s string) string

type RedirectPolicy

type RedirectPolicy struct {
	Max                   int
	SameHostOnly          bool
	HTTPSOnly             bool
	StripSensitiveHeaders bool
}

RedirectPolicy controls redirects.

type Reliability

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

func NewReliability

func NewReliability(cfg ReliabilityConfig) (*Reliability, error)

func (*Reliability) ApplyPolicy

func (r *Reliability) ApplyPolicy(c Ctx, p ReliabilityPolicy) error

ApplyPolicy runs a route reliability policy against a request. Reusable middleware construction lives in mw/reliability.

func (*Reliability) BeginTx

func (r *Reliability) BeginTx(ctx context.Context) (ReliabilityTx, error)

func (*Reliability) Close

func (r *Reliability) Close() error

func (*Reliability) Compact

func (r *Reliability) Compact(ctx context.Context) (MaintenanceReport, error)

func (*Reliability) IdempotencyStore

func (r *Reliability) IdempotencyStore() IdempotencyRepository

func (*Reliability) Inbox

func (r *Reliability) Inbox() *Inbox

func (*Reliability) Journal

func (r *Reliability) Journal() RequestJournalStore

func (*Reliability) Middleware

func (r *Reliability) Middleware() HandlerFunc

func (*Reliability) Outbox

func (r *Reliability) Outbox() *Outbox

func (*Reliability) PurgeExpiredIdempotency

func (r *Reliability) PurgeExpiredIdempotency(ctx context.Context, now time.Time) (int, error)

PurgeExpiredIdempotency removes expired replay records when the configured repository supports cleanup. File, memory and SQL adapters implement this.

func (*Reliability) Queue

func (r *Reliability) Queue() *DurableQueue

func (*Reliability) Repair

func (r *Reliability) Repair(ctx context.Context) error

func (*Reliability) Start

func (r *Reliability) Start() error

type ReliabilityConfig

type ReliabilityConfig struct {
	Enabled bool
	DataDir string

	JournalEnabled     bool
	IdempotencyEnabled bool
	QueueEnabled       bool

	// JournalStore, IdempotencyRepository and QueueStorage allow applications to
	// replace the default file-backed persistence with SQLite, PostgreSQL, Redis,
	// cloud storage, or any other durable backend. When nil, fh uses the built-in
	// file/directory backend under DataDir.
	JournalStore          RequestJournalStore
	IdempotencyRepository IdempotencyRepository
	QueueStorage          QueueStorage

	RequestIDHeader string

	IdempotencyHeader            string
	RequireIdempotencyKey        bool
	IdempotencyTTL               time.Duration
	IdempotencyProcessingStatus  int
	IdempotencyReplayHeaderValue string

	QueueDir                   string
	QueueWorkers               int
	QueueMaxAttempts           int
	QueuePollInterval          time.Duration
	QueueBackoff               time.Duration
	QueueConcurrencyLimitByKey bool
	QueueLogError              func(msg string, args ...any)
}

type ReliabilityPolicy

type ReliabilityPolicy struct {
	Enabled                bool
	RequireIdempotency     bool
	Journal                bool
	ReplayResponse         bool
	ConflictOnBodyDrift    bool
	MaxReplayAge           time.Duration
	IdempotencyKey         func(Ctx) string
	IdempotencyFingerprint func(Ctx) string
	Data                   DataPolicy
	Queue                  bool
	QueueType              string
	QueuePriority          int
	QueueDelay             time.Duration
	ConcurrencyKey         func(Ctx) string
}

type ReliabilityTx

type ReliabilityTx interface {
	Journal() RequestJournalStore
	Idempotency() IdempotencyRepository
	Queue() QueueStorage
	Commit() error
	Rollback() error
}

type ReloadHook

type ReloadHook func(new, old *ConfigGeneration)

ReloadHook is called after a successful reload.

type ReloadResult

type ReloadResult struct {
	Success    bool
	Generation ConfigGeneration
	Duration   time.Duration
	Error      error
}

ReloadResult holds the outcome of a configuration reload attempt.

type Request

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

Request is a fluent, allocation-conscious request builder.

func (*Request) AddHeader

func (r *Request) AddHeader(k, v string) *Request

func (*Request) Body

func (r *Request) Body(v any) *Request

func (*Request) BodyLimit

func (r *Request) BodyLimit(n int64) *Request

func (*Request) Bytes

func (r *Request) Bytes(b []byte, ct ...string) *Request

func (*Request) Connect

func (r *Request) Connect(ctx context.Context, u string) (*Response, error)

func (*Request) Cookie

func (r *Request) Cookie(c *http.Cookie) *Request

func (*Request) Decode

func (r *Request) Decode(v any) *Request

func (*Request) DecodeError

func (r *Request) DecodeError(v any) *Request

func (*Request) Delete

func (r *Request) Delete(ctx context.Context, u string) (*Response, error)

func (*Request) Do

func (r *Request) Do(ctx context.Context, method, rawurl string) (*Response, error)

func (*Request) Form

func (r *Request) Form(values url.Values) *Request

func (*Request) Get

func (r *Request) Get(ctx context.Context, u string) (*Response, error)

func (*Request) Head

func (r *Request) Head(ctx context.Context, u string) (*Response, error)

func (*Request) Header

func (r *Request) Header(k, v string) *Request

func (*Request) Headers

func (r *Request) Headers(h map[string]string) *Request

func (*Request) IdempotencyKey

func (r *Request) IdempotencyKey(k string) *Request

func (*Request) JSON

func (r *Request) JSON(v any) *Request

func (*Request) Meta

func (r *Request) Meta(k string, v any) *Request

func (*Request) Method

func (r *Request) Method(ctx context.Context, method, u string) (*Response, error)

func (*Request) Multipart

func (r *Request) Multipart(fields map[string]string, files ...UploadFile) *Request

func (*Request) Options

func (r *Request) Options(ctx context.Context, u string) (*Response, error)

func (*Request) Param

func (r *Request) Param(k, v string) *Request

func (*Request) Patch

func (r *Request) Patch(ctx context.Context, u string) (*Response, error)

func (*Request) Post

func (r *Request) Post(ctx context.Context, u string) (*Response, error)

func (*Request) Put

func (r *Request) Put(ctx context.Context, u string) (*Response, error)

func (*Request) Query

func (r *Request) Query(k, v string) *Request

func (*Request) QueryMap

func (r *Request) QueryMap(values map[string]string) *Request

func (*Request) QueryRaw

func (r *Request) QueryRaw(raw string) *Request

func (*Request) QuerySet

func (r *Request) QuerySet(k, v string) *Request

func (*Request) QueryValues

func (r *Request) QueryValues(values url.Values) *Request

func (*Request) Reader

func (r *Request) Reader(rd io.Reader, ct ...string) *Request

func (*Request) ResponseLimit

func (r *Request) ResponseLimit(n int64) *Request

func (*Request) Retry

func (r *Request) Retry(p RetryPolicy) *Request

func (*Request) Send

func (r *Request) Send(ctx context.Context, method, u string) (*Response, error)

func (*Request) Stream

func (r *Request) Stream() *Request

func (*Request) String

func (r *Request) String(s string, ct ...string) *Request

func (*Request) Timeout

func (r *Request) Timeout(d time.Duration) *Request

func (*Request) Trace

func (r *Request) Trace(ctx context.Context, u string) (*Response, error)

func (*Request) Use

func (r *Request) Use(m ...ClientMiddleware) *Request

type RequestHeader

type RequestHeader struct {
	Method []byte
	URI    []byte
	// RequestTarget is the exact target from the request line. URI is kept as
	// the compatibility alias used by older handlers.
	RequestTarget []byte
	Path          []byte
	QueryString   []byte
	Proto         []byte
	Host          []byte

	ContentType                 []byte
	Expect                      []byte
	Upgrade                     []byte
	HTTP2Settings               []byte
	ContentLength               int
	HasContentLength            bool
	KeepAlive                   bool
	Chunked                     bool
	UnsupportedTransferEncoding bool
	// contains filtered or unexported fields
}

RequestHeader holds parsed request metadata. All fields are slices into the underlying read buffer — no allocations during parse.

func (*RequestHeader) Add

func (h *RequestHeader) Add(name, value string)

Add appends a request header value without replacing existing values.

func (*RequestHeader) Del

func (h *RequestHeader) Del(name string)

Del removes every value for a request header.

func (*RequestHeader) Get

func (h *RequestHeader) Get(name string, defaults ...string) string

Get is the string-based, Fiber-style request header accessor.

func (*RequestHeader) GetHeaders

func (h *RequestHeader) GetHeaders() map[string][]string

GetHeaders returns all request headers and preserves repeated fields.

func (*RequestHeader) Init

func (h *RequestHeader) Init()

func (*RequestHeader) Peek

func (h *RequestHeader) Peek(name []byte) []byte

Peek returns the value of a header by name (case-insensitive). Returns nil if not found. Zero allocation.

func (*RequestHeader) PeekStr

func (h *RequestHeader) PeekStr(name string) string

PeekStr returns header value as string (allocates once for the string return).

func (*RequestHeader) Set

func (h *RequestHeader) Set(name, value string)

Set replaces all existing values for name with value.

func (*RequestHeader) SetCookie

func (h *RequestHeader) SetCookie(c *DefaultCtx, name, value string)

func (*RequestHeader) Values

func (h *RequestHeader) Values(name string) []string

Values returns every value stored for a request header.

type RequestJournal

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

func OpenRequestJournal

func OpenRequestJournal(path string) (*RequestJournal, error)

func (*RequestJournal) Append

func (*RequestJournal) Close

func (j *RequestJournal) Close() error

func (*RequestJournal) Path

func (j *RequestJournal) Path() string

type RequestJournalEntry

type RequestJournalEntry struct {
	RequestID string    `json:"request_id"`
	Event     string    `json:"event"`
	Method    string    `json:"method,omitempty"`
	Path      string    `json:"path,omitempty"`
	Status    int       `json:"status,omitempty"`
	BodyHash  string    `json:"body_hash,omitempty"`
	RemoteIP  string    `json:"remote_ip,omitempty"`
	Time      time.Time `json:"time"`
}

type RequestJournalStore

type RequestJournalStore interface {
	Append(RequestJournalEntry) error
	Close() error
}

RequestJournalStore is the durable append-only request lifecycle store. Implement this interface for DBMS-backed audit tables.

type RequestLifecycle

type RequestLifecycle struct {
	State  LifecycleState
	Events []RequestJournalEntry
	// contains filtered or unexported fields
}

func (*RequestLifecycle) Mark

func (l *RequestLifecycle) Mark(c Ctx, state LifecycleState)

type ResettableCodec

type ResettableCodec interface {
	Codec
	Reset()
}

ResettableCodec is optional for codecs that own reusable internal buffers.

type Response

type Response struct {
	Raw     *http.Response
	Request *http.Request
	// contains filtered or unexported fields
}

Response wraps http.Response with safe helpers.

func (*Response) Bytes

func (r *Response) Bytes() ([]byte, error)

func (*Response) Close

func (r *Response) Close() error

Close closes the response body without draining.

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

func (*Response) Decode

func (r *Response) Decode(v any) error

func (*Response) DownloadTo

func (r *Response) DownloadTo(w io.Writer) (int64, error)

DownloadTo streams a response body to a writer without buffering it all in memory.

func (*Response) DrainAndClose

func (r *Response) DrainAndClose() error

func (*Response) Header

func (r *Response) Header() http.Header

func (*Response) IsError

func (r *Response) IsError() bool

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

func (*Response) Reader

func (r *Response) Reader() io.ReadCloser

func (*Response) Save

func (r *Response) Save(path string, perm os.FileMode) error

func (*Response) SaveAtomic

func (r *Response) SaveAtomic(path string, perm os.FileMode) error

SaveAtomic writes a response to path through a temporary file and atomic rename.

func (*Response) StatusCode

func (r *Response) StatusCode() int

func (*Response) String

func (r *Response) String() (string, error)

type ResponseConn

type ResponseConn struct {
	net.Conn
	// contains filtered or unexported fields
}

ResponseConn wraps a net.Conn and provides WriteHeader, Write, and SetHeader methods for writing HTTP responses cleanly. It satisfies the net.Conn interface.

func (*ResponseConn) Read

func (rc *ResponseConn) Read(p []byte) (int, error)

Read reads from the underlying connection, serving any buffered prefix first.

func (*ResponseConn) SetHeader

func (rc *ResponseConn) SetHeader(key, value []byte)

SetHeader buffers a header to be written with the next WriteHeader call. If the header already exists, its value is updated.

func (*ResponseConn) StatusCode

func (rc *ResponseConn) StatusCode() int

StatusCode returns the status code set by WriteHeader, or 0 if not yet set.

func (*ResponseConn) Write

func (rc *ResponseConn) Write(p []byte) (int, error)

Write writes body data to the connection. If WriteHeader has not been called, it sends a 200 OK response first.

func (*ResponseConn) WriteHeader

func (rc *ResponseConn) WriteHeader(statusCode int)

WriteHeader sends the HTTP status line and any buffered headers. It must be called before Write for custom status codes and headers.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts   int
	MaxElapsed    time.Duration
	BaseDelay     time.Duration
	MaxDelay      time.Duration
	Jitter        bool
	RetryStatuses map[int]bool
	RetryMethods  map[string]bool
	RetryAfter    bool
	Predicate     func(*http.Response, error) bool
}

RetryPolicy controls safe retries. By default only idempotent methods are retried.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

func NoRetry

func NoRetry() RetryPolicy

type RoundRobinSelector

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

func NewRoundRobinSelector

func NewRoundRobinSelector(raw ...string) (*RoundRobinSelector, error)

func (*RoundRobinSelector) Next

func (r *RoundRobinSelector) Next(*http.Request) (*url.URL, error)

func (*RoundRobinSelector) Report

type RouteInfo

type RouteInfo struct {
	Method         string              `json:"method"`
	Path           string              `json:"path"`
	Name           string              `json:"name,omitempty"`
	Typed          bool                `json:"typed,omitempty"`
	RequestType    string              `json:"request_type,omitempty"`
	ResponseType   string              `json:"response_type,omitempty"`
	RequestSchema  JSONSchema          `json:"request_schema,omitempty"`
	ResponseSchema JSONSchema          `json:"response_schema,omitempty"`
	Deprecated     bool                `json:"deprecated,omitempty"`
	Tags           []string            `json:"tags,omitempty"`
	Security       RouteSecurityConfig `json:"security,omitempty"`
	Data           DataPolicy          `json:"data,omitempty"`
	Meta           map[string]any      `json:"meta,omitempty"`
	Handlers       []HandlerFunc       `json:"-"`
}

type RoutePattern

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

RoutePattern is an immutable, compiled route path matcher. It uses the same trie insertion, precedence, path cleanup, parameter, and wildcard logic as Router. It is useful for middleware that needs router-identical path matching.

func CompileRoutePattern

func CompileRoutePattern(pattern string) *RoutePattern

CompileRoutePattern compiles one router path pattern. Supported forms are static segments, :named parameters, and terminal * or *named wildcards.

func (*RoutePattern) Match

func (p *RoutePattern) Match(path string, params *[]Param) bool

Match matches path and appends captured values to params. Query strings are ignored. Captures are immutable substrings of the input string, so they stay valid after Match returns without requiring per-parameter allocations.

type RouteSecurityConfig

type RouteSecurityConfig struct {
	AuthRequired        bool          `json:"auth_required,omitempty"`
	MFARequired         bool          `json:"mfa_required,omitempty"`
	Scopes              []string      `json:"scopes,omitempty"`
	Roles               []string      `json:"roles,omitempty"`
	AuditRequired       bool          `json:"audit_required,omitempty"`
	IdempotencyRequired bool          `json:"idempotency_required,omitempty"`
	SignedRequired      bool          `json:"signed_required,omitempty"`
	ReplayProtected     bool          `json:"replay_protected,omitempty"`
	BodyLimit           int64         `json:"body_limit,omitempty"`
	Timeout             time.Duration `json:"timeout,omitempty"`
	RateLimitProfile    string        `json:"rate_limit_profile,omitempty"`
	DataClass           string        `json:"data_class,omitempty"`
}

type Router

type Router struct {

	// If true, route params are converted from []byte to string without allocation.
	//
	// Zero-copy params are only safe when:
	//   - request path buffer lives until the handler finishes
	//   - params are not stored after request completion
	//   - params are not used asynchronously after request completion
	//
	// Default false is safer.
	UnsafeParams bool
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) Add

func (r *Router) Add(method, path string, h HandlerFunc)

func (*Router) AddNamed

func (r *Router) AddNamed(method, path, name string, h HandlerFunc)

AddNamed registers a route and gives it a name for reverse URL generation.

func (*Router) Allowed

func (r *Router) Allowed(path []byte) []string

Allowed returns methods that match path in deterministic order.

Behavior:

  • if GET matches and HEAD is not registered, HEAD is included
  • if any method matches, OPTIONS is included

func (*Router) Find

func (r *Router) Find(method, path string, params *[]Param) HandlerFunc

func (*Router) FindBytes

func (r *Router) FindBytes(method, path []byte, params *[]Param) HandlerFunc

func (*Router) FindPrebuiltResponseBytes

func (r *Router) FindPrebuiltResponseBytes(method, path []byte) []byte

func (*Router) Freeze

func (r *Router) Freeze()

Freeze makes the router read-only. Call this after registering all routes and before serving traffic.

After Freeze(), Find/FindBytes/Allowed/Methods use lock-free reads.

func (*Router) Methods

func (r *Router) Methods() []string

func (*Router) Name

func (r *Router) Name(method, path, name string)

Name assigns a unique name to an already registered route.

func (*Router) URL

func (r *Router) URL(name string, values ...map[string]string) (string, error)

URL builds a path for a named route. Unused values are appended as a deterministically ordered query string.

func (*Router) URLWithQuery

func (r *Router) URLWithQuery(name string, params map[string]any, query map[string]any) (string, error)

URLWithQuery builds a URL for a named route using path params and appends URL-encoded query parameters.

type RuntimeInfo

type RuntimeInfo struct {
	Time       time.Time           `json:"time"`
	GoVersion  string              `json:"go_version"`
	Goroutines int                 `json:"goroutines"`
	Draining   bool                `json:"draining"`
	Routes     int                 `json:"routes"`
	Queue      QueueStats          `json:"queue,omitempty"`
	Config     SafeConfig          `json:"config"`
	Health     []HealthCheckResult `json:"health,omitempty"`
	Kernel     KernelRuntimeInfo   `json:"kernel"`
}

type SLO

type SLO struct {
	// Availability is the target availability (0.0-1.0). Example: 0.9999 = 99.99%.
	Availability float64

	// P99Latency is the target 99th percentile latency.
	P99Latency time.Duration

	// P95Latency is the target 95th percentile latency.
	P95Latency time.Duration

	// P50Latency is the target 50th percentile latency (median).
	P50Latency time.Duration

	// ErrorBudget is the total error budget window.
	ErrorBudget time.Duration

	// BurnRateWindow is the sliding window for burn rate calculation.
	// Default: 5 minutes.
	BurnRateWindow time.Duration
}

SLO defines a Service Level Objective for a route.

type SLOSnapshot

type SLOSnapshot struct {
	Route                string    `json:"route"`
	TotalRequests        int64     `json:"total_requests"`
	FailedRequests       int64     `json:"failed_requests"`
	SuccessRequests      int64     `json:"success_requests"`
	WindowRequests       int64     `json:"window_requests"`
	WindowFailed         int64     `json:"window_failed"`
	BurnRate             float64   `json:"burn_rate"`
	ErrorBudgetRemaining float64   `json:"error_budget_remaining"`
	Compliant            bool      `json:"compliant"`
	LastUpdate           time.Time `json:"last_update"`
	P50                  float64   `json:"p50_ms"`
	P95                  float64   `json:"p95_ms"`
	P99                  float64   `json:"p99_ms"`
}

SLOSnapshot is a read-only snapshot of SLO state (safe to copy).

type SLOTracker

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

SLOTracker tracks SLO compliance across routes. Routes are registered with router-style patterns and matched by the Handler middleware.

func NewSLOTracker

func NewSLOTracker(cfg ...SLOTrackerConfig) *SLOTracker

NewSLOTracker creates a new SLO tracker.

func (*SLOTracker) BurnRate

func (t *SLOTracker) BurnRate(route string) float64

BurnRate returns the current error burn rate for a route.

func (*SLOTracker) GetState

func (t *SLOTracker) GetState(route string) (SLOSnapshot, bool)

GetState returns the current SLO state for a route pattern.

func (*SLOTracker) Handler

func (t *SLOTracker) Handler() HandlerFunc

Handler returns middleware that tracks SLO compliance for every request whose path matches a registered pattern. Unmatched requests pass through with no overhead beyond the (cached) match lookup.

tracker.Register("/api/users/:id", fh.SLO{...})
app.Use(tracker.Handler())

func (*SLOTracker) IsCompliant

func (t *SLOTracker) IsCompliant(route string) bool

IsCompliant reports whether a route is currently meeting its SLO. Unregistered routes are considered compliant.

func (*SLOTracker) Match

func (t *SLOTracker) Match(path string) (route string, ok bool)

Match resolves a concrete request path to its registered SLO route. Precedence: exact static match, then dynamic patterns most-specific first, then regex patterns in registration order.

func (*SLOTracker) RecordRequest

func (t *SLOTracker) RecordRequest(route string, latency time.Duration, failed bool)

RecordRequest records a completed request for SLO tracking against an exact registered pattern. Prefer Handler for automatic path matching.

func (*SLOTracker) Register

func (t *SLOTracker) Register(pattern string, slo SLO)

Register registers an SLO for a route pattern. Supported pattern forms:

  • static paths: /api/users
  • named parameters: /api/users/:id, /api/users/:id/posts/:postID
  • terminal wildcards: /files/*, /files/*filepath
  • regular expressions: any pattern starting with "^", e.g. ^/api/v[0-9]+/users$

Non-regex patterns use the router's own matching semantics, so an SLO pattern matches exactly the paths the equivalent route would serve. Registering the same pattern again replaces the previous SLO. Register panics if a regex pattern does not compile (configuration error).

func (*SLOTracker) Snapshot

func (t *SLOTracker) Snapshot() map[string]SLOSnapshot

Snapshot returns a copy of all SLO states keyed by registered pattern.

func (*SLOTracker) Stop

func (t *SLOTracker) Stop()

Stop halts the background SLO checker.

func (*SLOTracker) Unregister

func (t *SLOTracker) Unregister(pattern string) bool

Unregister removes a route's SLO. It reports whether the pattern was registered.

type SLOTrackerConfig

type SLOTrackerConfig struct {
	// CheckInterval is how often to recalculate SLO state. Default: 10 seconds.
	CheckInterval time.Duration

	// AlertThreshold is the burn rate threshold that triggers an alert. Default: 2.0.
	AlertThreshold float64

	// OnAlert is called when an SLO violation is detected.
	OnAlert func(route string, state SLOSnapshot)

	// OnRecovery is called when an SLO recovers after a violation.
	OnRecovery func(route string, state SLOSnapshot)

	// MaxLatencySamples is the maximum number of latency samples per route. Default: 10000.
	MaxLatencySamples int
}

SLOTrackerConfig configures the SLO tracker.

type SSE

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

SSE is a streaming controller for Server-Sent Events connections.

func (*SSE) Comment

func (s *SSE) Comment(comment string) error

Comment sends a comment line (ignored by client JavaScript EventSource, useful for heartbeats/pings).

func (*SSE) Context

func (s *SSE) Context() context.Context

Context returns the request context, which is canceled when the client disconnects.

func (*SSE) Done

func (s *SSE) Done() <-chan struct{}

Done returns a channel that is closed when the client connection terminates.

func (*SSE) Ping

func (s *SSE) Ping() error

Ping sends an empty comment ping (`: ping\n\n`) to keep the connection alive through proxy timeouts.

func (*SSE) Send

func (s *SSE) Send(data any) error

Send sends data with no custom event type (defaults to standard "message" event).

func (*SSE) SendEvent

func (s *SSE) SendEvent(event string, data any) error

SendEvent sends data with a specific event type.

func (*SSE) SetRetry

func (s *SSE) SetRetry(d time.Duration) error

SetRetry informs the client how long to wait before attempting to reconnect.

func (*SSE) WriteEvent

func (s *SSE) WriteEvent(ev SSEEvent) error

WriteEvent formats and sends a single SSE event frame to the stream.

type SSEEvent

type SSEEvent struct {
	ID      string
	Event   string
	Data    any
	Retry   time.Duration
	Comment string
}

SSEEvent represents an individual Server-Sent Event frame.

type SafeConfig

type SafeConfig struct {
	SecureByDefault       bool              `json:"secure_by_default"`
	ReadTimeout           string            `json:"read_timeout,omitempty"`
	ReadHeaderTimeout     string            `json:"read_header_timeout,omitempty"`
	RequestBodyTimeout    string            `json:"request_body_timeout,omitempty"`
	WriteTimeout          string            `json:"write_timeout,omitempty"`
	HandlerTimeout        string            `json:"handler_timeout,omitempty"`
	IdleTimeout           string            `json:"idle_timeout,omitempty"`
	TLSHandshakeTimeout   string            `json:"tls_handshake_timeout,omitempty"`
	HTTP2IdleTimeout      string            `json:"http2_idle_timeout,omitempty"`
	MaxConnections        int               `json:"max_connections"`
	MaxConnectionsPerIP   int               `json:"max_connections_per_ip"`
	MaxInFlightRequests   int64             `json:"max_in_flight_requests"`
	MaxGoroutines         int               `json:"max_goroutines"`
	MaxHeapBytes          uint64            `json:"max_heap_bytes"`
	H2CEnabled            bool              `json:"h2c_enabled"`
	MaxRequestBodySize    int               `json:"max_request_body_size"`
	MaxHeaderListSize     int               `json:"max_header_list_size"`
	MaxHeaderCount        int               `json:"max_header_count"`
	MaxRequestLineSize    int               `json:"max_request_line_size"`
	ReliabilityEnabled    bool              `json:"reliability_enabled"`
	JournalEnabled        bool              `json:"journal_enabled"`
	IdempotencyEnabled    bool              `json:"idempotency_enabled"`
	QueueEnabled          bool              `json:"queue_enabled"`
	AuditEnabled          bool              `json:"audit_enabled"`
	RedactionEnabled      bool              `json:"redaction_enabled"`
	ComplianceEnabled     bool              `json:"compliance_enabled"`
	ComplianceProfile     ComplianceProfile `json:"compliance_profile,omitempty"`
	SecurityEventEndpoint bool              `json:"security_event_endpoint"`
	KernelEnabled         bool              `json:"kernel_enabled"`
	KernelBackend         KernelBackend     `json:"kernel_backend,omitempty"`
}

SafeConfig is a redacted summary of runtime configuration.

type SameSite

type SameSite int8
const (
	SameSiteLax SameSite = iota
	SameSiteStrict
	SameSiteNone
)

type SecureEnvelope

type SecureEnvelope struct {
	Version    int       `json:"version"`
	KeyID      string    `json:"key_id"`
	Nonce      []byte    `json:"nonce,omitempty"`
	Ciphertext []byte    `json:"ciphertext,omitempty"`
	Plaintext  []byte    `json:"plaintext,omitempty"`
	BodyHash   string    `json:"body_hash"`
	CreatedAt  time.Time `json:"created_at"`
}

func SealEnvelope

func SealEnvelope(policy DataPolicy, b []byte) (SecureEnvelope, error)

type SecurityEvent

type SecurityEvent struct {
	Type, RequestID, Path, Method, IP string
	Data                              map[string]any
	Time                              time.Time
}

Security events.

type SecurityEventSink

type SecurityEventSink interface{ Emit(SecurityEvent) }

type SecurityEventStream

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

func NewSecurityEventStream

func NewSecurityEventStream(max int) *SecurityEventStream

func (*SecurityEventStream) AddSink

func (s *SecurityEventStream) AddSink(sink SecurityEventSink)

func (*SecurityEventStream) Emit

func (*SecurityEventStream) Handler

func (s *SecurityEventStream) Handler() HandlerFunc

type SecurityFinding

type SecurityFinding struct {
	Severity string `json:"severity"`
	Code     string `json:"code"`
	Message  string `json:"message"`
	Fix      string `json:"fix,omitempty"`
	Route    string `json:"route,omitempty"`
}

SecurityFinding is returned by ValidateSecurity and the compliance endpoints.

type ServerMetrics

type ServerMetrics struct {
	ActiveConns          int64  `json:"active_conns"`
	TotalRequests        uint64 `json:"total_requests"`
	TotalErrors          uint64 `json:"total_errors"`
	Status2xx            uint64 `json:"status_2xx"`
	Status3xx            uint64 `json:"status_3xx"`
	Status4xx            uint64 `json:"status_4xx"`
	Status5xx            uint64 `json:"status_5xx"`
	TotalDurationNS      uint64 `json:"total_duration_ns"`
	MaxRequestDurationNS uint64 `json:"max_request_duration_ns"`
}

ServerMetrics contains real-time server runtime metrics.

type ServerTLSOptions

type ServerTLSOptions struct {
	Certificates              []tls.Certificate
	GetCertificate            func(*tls.ClientHelloInfo) (*tls.Certificate, error)
	ClientCAs                 *x509.CertPool
	RequireClientCertificate  bool
	VerifyClientCertIfPresent bool
	MinVersion                uint16
	NextProtos                []string
	CurvePreferences          []tls.CurveID
}

ServerTLSOptions builds a hardened server-side tls.Config without coupling the HTTP runtime to certificate provisioning. TLS 1.3 is the default; set MinVersion to tls.VersionTLS12 only when compatibility requires it.

type ServiceClient

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

ServiceClient is a lightweight per-service view over Client with base path, shared headers and middleware.

func (*ServiceClient) Connect

func (s *ServiceClient) Connect(ctx context.Context, p string) (*Response, error)

func (*ServiceClient) Delete

func (s *ServiceClient) Delete(ctx context.Context, p string) (*Response, error)

func (*ServiceClient) Do

func (s *ServiceClient) Do(ctx context.Context, method, p string, body ...any) (*Response, error)

func (*ServiceClient) Get

func (s *ServiceClient) Get(ctx context.Context, p string) (*Response, error)

func (*ServiceClient) Head

func (s *ServiceClient) Head(ctx context.Context, p string) (*Response, error)

func (*ServiceClient) Header

func (s *ServiceClient) Header(k, v string) *ServiceClient

func (*ServiceClient) Options

func (s *ServiceClient) Options(ctx context.Context, p string) (*Response, error)

func (*ServiceClient) Patch

func (s *ServiceClient) Patch(ctx context.Context, p string, body any) (*Response, error)

func (*ServiceClient) Post

func (s *ServiceClient) Post(ctx context.Context, p string, body any) (*Response, error)

func (*ServiceClient) Put

func (s *ServiceClient) Put(ctx context.Context, p string, body any) (*Response, error)

func (*ServiceClient) Query

func (s *ServiceClient) Query(ctx context.Context, p string, body any) (*Response, error)

func (*ServiceClient) R

func (s *ServiceClient) R() *Request

func (*ServiceClient) Search

func (s *ServiceClient) Search(ctx context.Context, p string, body any) (*Response, error)

func (*ServiceClient) Trace

func (s *ServiceClient) Trace(ctx context.Context, p string) (*Response, error)

func (*ServiceClient) Use

type SharedStateProvider

type SharedStateProvider = kv.Provider

SharedStateProvider is the application-level shared-state contract. It is an alias of kv.Provider so applications can configure state without depending on a concrete memory, file, Redis, or PostgreSQL implementation.

type StartupBannerConfig

type StartupBannerConfig struct {
	// Disabled suppresses the startup banner entirely.
	Disabled bool
	// Name is the framework/application name shown in the banner. Default: "fh".
	Name string
	// Version is an optional application/framework version string.
	Version string
	// Subtitle is an optional short description below the title.
	Subtitle string
	// Scheme is used to build the displayed URL. Default: "http".
	Scheme string
	// Address overrides the listener address shown in the banner.
	Address string
	// ASCIIArt overrides the default small ASCII wordmark. Set to "-" to hide it.
	ASCIIArt string
	// Color enables ANSI color output. It is disabled by default so logs remain
	// clean when stdout is captured by process managers.
	Color bool
	// Writer receives the banner. Default: os.Stdout.
	Writer io.Writer
	// Render allows complete custom rendering. When set, fh passes StartupBannerData
	// and prints the returned string as-is. data.SecureDefaultsNotice (when
	// non-empty) is still appended after Render's output unless
	// HideSecureDefaultsNotice is set — render it yourself from data and set
	// HideSecureDefaultsNotice to avoid it appearing twice.
	Render func(StartupBannerData) string
	// ExtraLines are appended as key/value rows after the built-in rows.
	ExtraLines []StartupBannerLine
	// HideRoutes hides the route count.
	HideRoutes bool
	// HidePID hides the current process id.
	HidePID bool
	// HideGoVersion hides runtime.Version().
	HideGoVersion bool
	// HideMode hides the configured fh mode.
	HideMode bool
	// HideSecureDefaultsNotice suppresses the printed reminder that
	// production mode / SecureByDefault bound protocol input and harden
	// response headers only — they do not add authentication, CSRF
	// protection, rate limiting, or a Host allow-list. Shown by default so
	// this is genuinely unmissable at process start, not just in
	// ValidateSecurity()/the compliance endpoints. Set once a team has
	// internalized the distinction.
	HideSecureDefaultsNotice bool
}

StartupBannerConfig controls the pretty ASCII startup message shown when the application starts serving. The default is enabled and writes to stdout. Disable it in tests, machine-readable logging environments, or embedded use.

type StartupBannerData

type StartupBannerData struct {
	Name      string
	Version   string
	Subtitle  string
	URL       string
	Address   string
	Scheme    string
	Routes    int
	PID       int
	GoVersion string
	Mode      Mode
	HTTP2     bool
	Extra     []StartupBannerLine
	// SecureDefaultsNotice is non-empty when the app is running in a mode
	// (or with SecureByDefault) where the boundary between "protocol/response
	// hardening is on" and "auth/CSRF/rate-limiting are on" is worth
	// restating at every boot. Empty means either the notice doesn't apply
	// (a permissive/benchmark mode) or it was explicitly hidden.
	SecureDefaultsNotice string
}

StartupBannerData is passed to custom startup banner renderers.

type StartupBannerLine

type StartupBannerLine struct {
	Key   string
	Value string
}

StartupBannerLine is one key/value row inside the startup banner.

type StaticConfig

type StaticConfig struct {
	// Compress enables gzip compression for text-like responses.
	Compress bool

	// MaxAge controls the Cache-Control max-age directive in seconds.
	// Zero omits the header. Superseded by CacheControl when both are set.
	MaxAge int

	// CacheControl, when non-empty, overrides the entire Cache-Control header
	// for all served files. Takes precedence over MaxAge.
	// Example: "public, max-age=86400, immutable"
	CacheControl string

	// Browse enables directory listing when no index file is found.
	Browse bool

	// Index is the filename used as a directory index. Default: "index.html".
	// Superseded by IndexFiles when both are set.
	Index string

	// IndexFiles is an ordered list of filenames tried as the directory index.
	// The first matching file is served. Takes precedence over Index.
	// Example: []string{"index.html", "index.htm", "default.html"}
	IndexFiles []string

	// CacheDuration limits how long file metadata is cached in memory.
	// Zero disables caching.
	CacheDuration time.Duration

	// StripSlash strips the trailing slash from the request path before
	// resolving the file. When true, both /dir and /dir/ serve the same
	// content without a redirect.
	StripSlash bool

	// ShowHidden includes dotfiles (e.g. .env, .git) in directory listings.
	// Defaults to false so accidental secrets/metadata in the served root
	// are not exposed through Browse.
	ShowHidden bool

	// NotFoundHandler, when non-nil, is called instead of returning a 404
	// when the requested file or directory is not found under the static root.
	// Useful for single-page applications: serve index.html for any unknown path.
	NotFoundHandler HandlerFunc

	// PreCompressed enables transparent serving of pre-compressed sidecar files.
	// When the client accepts br (Brotli), fh checks for <path>.br before <path>.
	// When the client accepts gzip, fh checks for <path>.gz before <path>.
	// The original Content-Type is preserved and Content-Encoding is set.
	PreCompressed bool

	// MaxRanges limits the number of byte ranges accepted in one request.
	// Zero uses the safe default of 16 ranges.
	MaxRanges int
}

StaticConfig configures static file serving behavior.

type StoredOutbox

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

func NewStoredOutbox

func NewStoredOutbox(cfg OutboxConfig) *StoredOutbox

func (*StoredOutbox) DispatchOnce

func (o *StoredOutbox) DispatchOnce(ctx context.Context, limit int) (int, error)

func (*StoredOutbox) List

func (o *StoredOutbox) List(ctx context.Context, state string, limit int) ([]OutboxMessage, error)

func (*StoredOutbox) Publish

func (o *StoredOutbox) Publish(ctx context.Context, topic string, payload any, headers map[string]string) (string, error)

type StreamWriter

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

StreamWriter writes an HTTP response incrementally. HTTP/1.1 uses chunked transfer encoding; HTTP/1.0 falls back to a close-delimited body.

func (*StreamWriter) Close

func (w *StreamWriter) Close() error

func (*StreamWriter) Flush

func (w *StreamWriter) Flush() error

func (*StreamWriter) Write

func (w *StreamWriter) Write(p []byte) (int, error)

type StructuredError

type StructuredError struct {
	Error     string       `json:"error"`
	Message   string       `json:"message,omitempty"`
	RequestID string       `json:"request_id,omitempty"`
	Fields    []FieldError `json:"fields,omitempty"`
}

type TemplateEngine

type TemplateEngine interface {
	Render(w io.Writer, name string, data any, layout ...string) error
}

TemplateEngine is the interface for template rendering engines. Implementations render named templates with data and optional layouts.

type TokenSource

type TokenSource interface {
	Token(context.Context) (string, error)
}

TokenSource supplies bearer tokens without binding the client to any OAuth package.

type TokenSourceFunc

type TokenSourceFunc func(context.Context) (string, error)

func (TokenSourceFunc) Token

func (f TokenSourceFunc) Token(ctx context.Context) (string, error)

type TypedResponse

type TypedResponse[T any] struct {
	Data   T          `json:"data"`
	Meta   *Meta      `json:"meta,omitempty"`
	Errors []APIError `json:"errors,omitempty"`
}

TypedResponse wraps a response with metadata for enhanced API responses.

func PaginatedResponse

func PaginatedResponse[T any](data []T, page, perPage int, total int64) TypedResponse[[]T]

PaginatedResponse creates a typed paginated response.

type UploadFile

type UploadFile struct {
	FieldName, FileName, ContentType string
	Reader                           io.Reader
	Path                             string
}

func File

func File(field, filename string, r io.Reader) UploadFile

func FilePath

func FilePath(field, p string) UploadFile

type ValidateConfig

type ValidateConfig struct {
	// Skip allows skipping validation for specific requests.
	Skip func(Ctx) bool
}

ValidateConfig configures the validation middleware.

type ValidationError

type ValidationError struct{ Fields []FieldError }

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationErrorBuilder

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

ValidationErrorBuilder accumulates field errors during validation.

func NewValidationErrorBuilder

func NewValidationErrorBuilder() *ValidationErrorBuilder

NewValidationErrorBuilder creates a new builder.

func (*ValidationErrorBuilder) Add

func (b *ValidationErrorBuilder) Add(field, code, message string)

Add appends a field error.

func (*ValidationErrorBuilder) Addf

func (b *ValidationErrorBuilder) Addf(field, code, format string, args ...any)

Addf appends a field error with formatted message.

func (*ValidationErrorBuilder) Clear

func (b *ValidationErrorBuilder) Clear()

Clear resets the builder.

func (*ValidationErrorBuilder) Error

Error returns a *ValidationError if errors were collected, nil otherwise.

func (*ValidationErrorBuilder) HasErrors

func (b *ValidationErrorBuilder) HasErrors() bool

HasErrors reports whether any errors were collected.

func (*ValidationErrorBuilder) ValidationErrors

func (b *ValidationErrorBuilder) ValidationErrors() ValidationErrors

ValidationErrors returns the raw field errors.

type ValidationErrors

type ValidationErrors []FieldError

ValidationErrors is a collection of field-level validation errors.

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

func (ValidationErrors) First

func (e ValidationErrors) First() *FieldError

First returns the first field error, or nil.

func (ValidationErrors) Get

func (e ValidationErrors) Get(field string) []FieldError

Get returns all field errors for the given field name.

func (ValidationErrors) Has

func (e ValidationErrors) Has(field string) bool

Has reports whether any field error matches the given field name.

func (ValidationErrors) MarshalJSON

func (e ValidationErrors) MarshalJSON() ([]byte, error)

MarshalJSON serializes as an array of field error objects.

func (ValidationErrors) Unwrap

func (e ValidationErrors) Unwrap() error

type ValidationRule

type ValidationRule struct {
	// Tag is the struct tag name (e.g., "validate").
	Tag string
	// Param is the optional parameter (e.g., "min=3" → Param="3").
	Param string
}

ValidationRule defines a single validation rule for a struct field.

type Validator

type Validator interface{ Validate() error }

Validator is implemented by request DTOs that can validate themselves.

type XDPConfig

type XDPConfig = kernel.XDPConfig

type XDPManager

type XDPManager = kernel.XDPManager

func NewXDPManager

func NewXDPManager(cfg XDPConfig) *XDPManager

type XDPMode

type XDPMode = kernel.XDPMode

Directories

Path Synopsis
cmd
fh-init command
fh-kernelctl command
contrib module
examples
basic command
http-modern command
kernel_server command
prefork command
Command prefork demonstrates fh's OS-process prefork supervisor and doubles as the target binary for prefork_integration_test.go, which drives it with real SIGHUP/SIGTERM signals to prove zero-downtime rolling restarts.
Command prefork demonstrates fh's OS-process prefork supervisor and doubles as the target binary for prefork_integration_test.go, which drives it with real SIGHUP/SIGTERM signals to prove zero-downtime rolling restarts.
rfc9421/client command
rfc9421/server command
secure_wasm command
internal
doccheck
Package doccheck extracts and validates the ```go fenced code blocks that appear in the project's Markdown documentation (docs/*.md and README.md).
Package doccheck extracts and validates the ```go fenced code blocks that appear in the project's Markdown documentation (docs/*.md and README.md).
mw
acceptquery
Package acceptquery advertises and enforces HTTP QUERY request formats as defined by RFC 10008.
Package acceptquery advertises and enforces HTTP QUERY request formats as defined by RFC 10008.
cache
Package cache provides bounded in-memory HTTP response caching.
Package cache provides bounded in-memory HTTP response caching.
coalesce
Package coalesce provides request coalescing middleware.
Package coalesce provides request coalescing middleware.
contentdigest
Package contentdigest implements RFC 9530 Content-Digest verification and response generation.
Package contentdigest implements RFC 9530 Content-Digest verification and response generation.
csrf
Package csrf implements a signed, browser-session-bound, origin-aware double-submit CSRF defense for fh.
Package csrf implements a signed, browser-session-bound, origin-aware double-submit CSRF defense for fh.
decompress
Package decompress provides bounded request decompression.
Package decompress provides bounded request decompression.
earlydata
Package earlydata protects non-idempotent requests replayed as TLS early data.
Package earlydata protects non-idempotent requests replayed as TLS early data.
fetchmetadata
Package fetchmetadata implements W3C Fetch Metadata Request Headers security policies.
Package fetchmetadata implements W3C Fetch Metadata Request Headers security policies.
httpsignature
Package httpsignature signs FH responses using the Ed25519 response profile implemented by pkg/httpsignature and the wire format defined by RFC 9421.
Package httpsignature signs FH responses using the Ed25519 response profile implemented by pkg/httpsignature and the wire format defined by RFC 9421.
policy
Package policy groups cross-cutting route metadata with middleware policies.
Package policy groups cross-cutting route metadata with middleware policies.
rewrite
Package rewrite performs bounded internal request rewrites.
Package rewrite performs bounded internal request rewrites.
securetransport
Package securetransport provides application-layer encrypted, device-bound, replay-resistant request/response transport for fh applications.
Package securetransport provides application-layer encrypted, device-bound, replay-resistant request/response transport for fh applications.
servertiming
Package servertiming provides Server-Timing header support per RFC 8638.
Package servertiming provides Server-Timing header support per RFC 8638.
skip
Package skip conditionally bypasses middleware.
Package skip conditionally bypasses middleware.
slidingwindow
Package slidingwindow provides a sliding window rate limiter middleware.
Package slidingwindow provides a sliding window rate limiter middleware.
smartcache
Package smartcache provides RFC 7234 compliant HTTP caching middleware.
Package smartcache provides RFC 7234 compliant HTTP caching middleware.
static
Package static serves files as route handlers with cache and download controls.
Package static serves files as route handlers with cache and download controls.
validate
Package validate provides request validation middleware for fh.
Package validate provides request validation middleware for fh.
pkg
config
Package config provides small dependency-free production configuration helpers for fh applications.
Package config provides small dependency-free production configuration helpers for fh applications.
hpack
Package hpack implements HPACK (RFC 7541), the HTTP/2 header compression format.
Package hpack implements HPACK (RFC 7541), the HTTP/2 header compression format.
httpsignature
Package httpsignature implements a strict RFC 9421 response-signature profile using Ed25519 and RFC 9530 Content-Digest fields.
Package httpsignature implements a strict RFC 9421 response-signature profile using Ed25519 and RFC 9530 Content-Digest fields.
httpsignature/httpclient
Package httpclient provides optional net/http convenience wrappers around github.com/oarkflow/fh/pkg/httpsignature's RFC 9421 response-signature verification.
Package httpclient provides optional net/http convenience wrappers around github.com/oarkflow/fh/pkg/httpsignature's RFC 9421 response-signature verification.
securetransport
Package securetransport implements the versioned binary protocol shared by the fh secure-transport middleware and its Go WebAssembly fetch client.
Package securetransport implements the versioned binary protocol shared by the fh secure-transport middleware and its Go WebAssembly fetch client.
storage/kv
Package kv provides the single low-level key-value storage primitive shared by fh's middleware packages (rate limiters, replay/nonce guards, response caches, reputation scores, allow-lists, admin registries, ...).
Package kv provides the single low-level key-value storage primitive shared by fh's middleware packages (rate limiters, replay/nonce guards, response caches, reputation scores, allow-lists, admin registries, ...).
wasm
cmd/manifest command
cmd/securefetch command

Jump to

Keyboard shortcuts

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