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
- Variables
- func AppendHeader(dst []byte, key, value string) []byte
- func AppendHeaderBytes(dst []byte, key, value []byte) []byte
- func AppendJSONString(dst []byte, s string) []byte
- func AppendJSONStringContent(dst []byte, s string) []byte
- func AppendJSONStringContentBytes(dst []byte, b []byte) []byte
- func AtomicHandoff(c Ctx, jobType string, payload any, opts ...QueueJob) (string, error)
- func Bind(c Ctx, v any) error
- func BindCookie(c Ctx, v any) error
- func BindForm(c Ctx, v any) error
- func BindHeader(c Ctx, v any) error
- func BindJSON(c Ctx, v any) error
- func BindParams(c Ctx, v any) error
- func BindQuery(c Ctx, v any) error
- func BuildXDP(source, output string) error
- func Bytes(s string) []byte
- func BytesEqualFold(a, b []byte) bool
- func ClientSecurityDialContext(sec ClientSecurity, base *net.Dialer) func(context.Context, string, string) (net.Conn, error)
- func ClientTraceParent(ctx context.Context, traceparent string) context.Context
- func ConstantTimeEqual(a, b string) bool
- func DecodeBody(data []byte, contentType string, v any) error
- func DecodeForm(data []byte, v any) error
- func DecodeHeaders(h *RequestHeader, v any) error
- func DefaultXDPPinPath(name string) string
- func DeleteResponseHeader(c Ctx, name string) bool
- func DetachXDP(iface string, mode XDPMode) error
- func DeterministicIdempotencyKey(parts ...string) string
- func EmitSecurityEvent(c Ctx, typ string, data map[string]any)
- func EncodeBody(contentType string, v any) ([]byte, error)
- func GetJSON[T any](ctx context.Context, c *Client, u string) (T, error)
- func HasHeaderToken(value []byte, token string) bool
- func InboxDedupeKey(source string, payload []byte) string
- func JSONMarshal(v any) ([]byte, error)
- func JSONTypeSupported(t reflect.Type, seen map[reflect.Type]bool) bool
- func JSONUnmarshal(data []byte, v any) error
- func MaskCard(v string) string
- func MaskEmail(v string) string
- func MustSetJSONEngine(engine JSONEngine)
- func Negotiate(ctx Ctx, offered []string) string
- func NewACMEManager(opt ACMEOptions) (*autocert.Manager, error)
- func NewServerTLSConfig(opt ServerTLSOptions) (*tls.Config, error)
- func OpenEnvelope(policy DataPolicy, env SecureEnvelope) ([]byte, error)
- func ParseCookie(header string) map[string]string
- func PostJSON[Req any, Res any](ctx context.Context, c *Client, u string, body Req) (Res, error)
- func ProblemDetails(c Ctx, status int, title, detail, typeURI string) error
- func PutJSON[Req any, Res any](ctx context.Context, c *Client, u string, body Req) (Res, error)
- func RedactSecret(s string) string
- func RedactSecrets(s string) string
- func RedactValue(key string, value any) any
- func RegisterCodec(c Codec)
- func RegisterCodecAlias(contentType string, c Codec)
- func RegisterCodecStrict(c Codec) error
- func RegisterRule(name string, fn ruleFunc)
- func RenderStartupBanner(cfg StartupBannerConfig, data StartupBannerData) string
- func ReplaceRequestBody(c Ctx, body []byte) bool
- func RequestTLSState(c Ctx) (tls.ConnectionState, bool)
- func ResetJSONEngine()
- func SSEvent(c Ctx, event string, data any) error
- func SetClientIP(c Ctx, value string) bool
- func SetCodecOptions(opt CodecOptions)
- func SetJSONEngine(engine JSONEngine) error
- func SetPrincipal(c Ctx, p Principal)
- func SignCookie(value string, secret []byte) string
- func StatusReason(code int) string
- func StrEqFold(b []byte, s string) bool
- func StreamJSON(ctx Ctx, fn func(json.Encoder) error) error
- func StreamNDJSON(ctx Ctx, fn func(yield func(any) bool)) error
- func TLSStateFromContext(ctx context.Context) (tls.ConnectionState, bool)
- func TenantID(c Ctx) string
- func TrimOWS(b []byte) []byte
- func ValidToken(b []byte) bool
- func ValidateStruct(s any) error
- func ValidateStructWith(s any) error
- func VerifyChain(checkpoints []MerkleCheckpoint) error
- func VerifyCheckpoint(cp MerkleCheckpoint, eventHashes []string) bool
- func VerifySignedCookie(s string, secret []byte) (string, bool)
- func WithBudget(ctx context.Context, b *Budget) context.Context
- func WithTLSState(ctx context.Context, state tls.ConnectionState) context.Context
- func WriteAll(w io.Writer, b []byte) error
- type ACMEOptions
- type APIError
- type App
- func (a *App) Add(method, path string, handlers ...HandlerFunc) *App
- func (a *App) AddHealthCheck(name string, timeout time.Duration, fn func(context.Context) error) *App
- func (a *App) All(path string, handlers ...HandlerFunc) *App
- func (a *App) AllTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) ComplianceControls() []ComplianceControl
- func (a *App) ComplianceReport() ComplianceReport
- func (a *App) Connect(path string, handlers ...HandlerFunc) *App
- func (a *App) ConnectTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Delete(path string, handlers ...HandlerFunc) *App
- func (a *App) DeleteTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) EnableComplianceEndpoints(prefix string, middleware ...HandlerFunc) *App
- func (a *App) EnableDocs(path string) *App
- func (a *App) EnableHealth(prefix string, middleware ...HandlerFunc) *App
- func (a *App) EnableOpenAPI(path string, cfg OpenAPIConfig) *App
- func (a *App) EnableRouteList(path string, middleware ...HandlerFunc) *App
- func (a *App) EnableRuntime(prefix string, middleware ...HandlerFunc) *App
- func (a *App) EnableSecurityEvents(path string) *SecurityEventStream
- func (a *App) EnableSwaggerUI(prefix string) *App
- func (a *App) ErrorCount(code string) uint64
- func (a *App) Get(path string, handlers ...HandlerFunc) *App
- func (a *App) GetTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Group(prefix string, handlers ...HandlerFunc) *Group
- func (a *App) Head(path string, handlers ...HandlerFunc) *App
- func (a *App) HeadTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) HealthCheck(path string, config HealthConfig) *App
- func (a *App) HealthStatus(ctx context.Context) (bool, []HealthCheckResult)
- func (a *App) Inbox() *Inbox
- func (a *App) IsDraining() bool
- func (a *App) KernelReadiness() KernelReadinessReport
- func (a *App) KernelRuntimeInfo() KernelRuntimeInfo
- func (a *App) Listen(addr string) error
- func (a *App) ListenAutoTLS(domains []string, cacheDir string) error
- func (a *App) ListenAutoTLSWithGracefulShutdown(domains []string, cacheDir string) error
- func (a *App) ListenContext(ctx context.Context, addr string) error
- func (a *App) ListenPrefork(addr string, opts ...PreforkOption) error
- func (a *App) ListenProxyProtocol(addr string, cfg ...ProxyProtocolConfig) error
- func (a *App) ListenTLS(addr, certFile, keyFile string) error
- func (a *App) ListenTLSContext(ctx context.Context, addr, certFile, keyFile string) error
- func (a *App) ListenTLSProxyProtocol(addr, certFile, keyFile string, cfg ...ProxyProtocolConfig) error
- func (a *App) ListenTLSWithGracefulShutdown(addr, certFile, keyFile string) error
- func (a *App) ListenUnix(path string) error
- func (a *App) ListenUnixContext(ctx context.Context, path string) error
- func (a *App) ListenWithGracefulShutdown(addr string) error
- func (a *App) Logger() Logger
- func (a *App) Meta(key string, val any) *App
- func (a *App) Metrics() ServerMetrics
- func (a *App) Mount(prefix string, sub *App) *App
- func (a *App) MustStateStore(namespace string) kv.Store
- func (a *App) Name(name string) *App
- func (a *App) OnClose(fn func(net.Conn)) *App
- func (a *App) OnConnect(fn func(net.Conn)) *App
- func (a *App) OnError(fn func(error)) *App
- func (a *App) OnListen(fn HookFunc) *App
- func (a *App) OnRoute(fn func(RouteInfo)) *App
- func (a *App) OnShutdown(fn HookFunc) *App
- func (a *App) OpenAPI() map[string]any
- func (a *App) OpenAPISpec() map[string]any
- func (a *App) Options(path string, handlers ...HandlerFunc) *App
- func (a *App) OptionsTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Outbox() *Outbox
- func (a *App) Patch(path string, handlers ...HandlerFunc) *App
- func (a *App) PatchTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Post(path string, handlers ...HandlerFunc) *App
- func (a *App) PostTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Purge(path string, handlers ...HandlerFunc) *App
- func (a *App) Put(path string, handlers ...HandlerFunc) *App
- func (a *App) PutTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Query(path string, handlers ...HandlerFunc) *App
- func (a *App) QueryTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) Queue() *DurableQueue
- func (a *App) REF() REFEngine
- func (a *App) Reliability() *Reliability
- func (a *App) Reload() error
- func (a *App) Report(path string, handlers ...HandlerFunc) *App
- func (a *App) RouteTreeString() string
- func (a *App) Routes() []RouteInfo
- func (a *App) RuntimeInfo() RuntimeInfo
- func (a *App) SafeConfig() SafeConfig
- func (a *App) Search(path string, handlers ...HandlerFunc) *App
- func (a *App) Serve(ln net.Listener) error
- func (a *App) ServeContext(ctx context.Context, ln net.Listener) error
- func (a *App) ServeTLS(ln net.Listener, config *tls.Config) error
- func (a *App) SetREF(engine REFEngine) *App
- func (a *App) Shutdown() error
- func (a *App) ShutdownWithContext(ctx context.Context) error
- func (a *App) ShutdownWithTimeout(d time.Duration) error
- func (a *App) StateStore(ctx context.Context, namespace string) (kv.Store, error)
- func (a *App) Static(prefix, root string, config ...StaticConfig) *App
- func (a *App) StaticFS(prefix string, filesystem fs.FS, config ...StaticConfig) *App
- func (a *App) Tag(tags ...string) *App
- func (a *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error)
- func (a *App) Trace(path string, handlers ...HandlerFunc) *App
- func (a *App) TraceTyped(path string, handler any, middleware ...HandlerFunc) *App
- func (a *App) URL(name string, params ...map[string]string) (string, error)
- func (a *App) URLWithQuery(name string, params map[string]any, query map[string]any) (string, error)
- func (a *App) Use(handlers ...HandlerFunc) *App
- func (a *App) ValidateKernelProduction() error
- func (a *App) ValidateSecurity() []SecurityFinding
- func (a *App) WithDataPolicy(p DataPolicy) *App
- func (a *App) WithRouteSecurity(cfg RouteSecurityConfig) *App
- func (a *App) WriteAudit(ctx context.Context, e AuditEvent) error
- type AtomicJobOptions
- type AtomicJobResult
- type AuditConfig
- type AuditEvent
- type AuditRecorder
- type AuditSink
- type AuditSinkCloser
- type BatchResult
- type Budget
- func (b *Budget) CanRetry(current int) bool
- func (b *Budget) CanUpstream() bool
- func (b *Budget) CheckBodySize(size int64) bool
- func (b *Budget) CheckMemory(bytes int64) bool
- func (b *Budget) Child(d time.Duration, split BudgetSplit) *Budget
- func (b *Budget) Expired() bool
- func (b *Budget) Remaining() time.Duration
- func (b *Budget) String() string
- func (b *Budget) WithDeadline(d time.Duration) *Budget
- type BudgetConfig
- type BudgetSplit
- type ByteRange
- type CertPinningConfig
- type CertificateReloader
- type CircuitBreaker
- type CircuitConfig
- type Client
- func (c *Client) Async(fn func(*Request) (*Response, error)) *FutureResponse
- func (c *Client) Batch(ctx context.Context, maxConcurrency int, ...) []BatchResult
- func (c *Client) Close() error
- func (c *Client) Connect(ctx context.Context, u string) (*Response, error)
- func (c *Client) Delete(ctx context.Context, u string) (*Response, error)
- func (c *Client) Do(ctx context.Context, method, u string, body ...any) (*Response, error)
- func (c *Client) Get(ctx context.Context, u string) (*Response, error)
- func (c *Client) Head(ctx context.Context, u string) (*Response, error)
- func (c *Client) Options(ctx context.Context, u string) (*Response, error)
- func (c *Client) Patch(ctx context.Context, u string, body any) (*Response, error)
- func (c *Client) Post(ctx context.Context, u string, body any) (*Response, error)
- func (c *Client) Put(ctx context.Context, u string, body any) (*Response, error)
- func (c *Client) Query(ctx context.Context, u string, body any) (*Response, error)
- func (c *Client) R() *Request
- func (c *Client) Search(ctx context.Context, u string, body any) (*Response, error)
- func (c *Client) Service(base string) *ServiceClient
- func (c *Client) Trace(ctx context.Context, u string) (*Response, error)
- func (c *Client) Use(m ...ClientMiddleware) *Client
- type ClientConfig
- type ClientError
- type ClientErrorKind
- type ClientEvent
- type ClientHooks
- type ClientMetrics
- type ClientMiddleware
- func ClientAPIKey(header, key string) ClientMiddleware
- func ClientBasicAuth(user, pass string) ClientMiddleware
- func ClientBearer(token string) ClientMiddleware
- func ClientBearerTokenSource(src TokenSource) ClientMiddleware
- func ClientBodyLimit(n int64) ClientMiddleware
- func ClientBulkhead(max int, wait time.Duration) ClientMiddleware
- func ClientCache(cache *MemoryHTTPCache) ClientMiddleware
- func ClientCircuitBreaker(cfg CircuitConfig) ClientMiddleware
- func ClientGzipRequest(min int) ClientMiddleware
- func ClientHMACSigner(header, secret string) ClientMiddleware
- func ClientHeader(k, v string) ClientMiddleware
- func ClientIdempotency(provider func(*http.Request) string) ClientMiddleware
- func ClientLoadBalance(sel EndpointSelector) ClientMiddleware
- func ClientLogger(l Logger) ClientMiddleware
- func ClientRateLimit(ratePerSecond int) ClientMiddleware
- func ClientRecover() ClientMiddleware
- func ClientRequestID(header string) ClientMiddleware
- func ClientRequireStatus(allow func(int) bool) ClientMiddleware
- func ClientTraceContext() ClientMiddleware
- type ClientSecurity
- type ClientStatsMetrics
- type Codec
- type CodecOptions
- type ComplianceConfig
- type ComplianceControl
- type ComplianceProfile
- type ComplianceReport
- type Config
- type ConfigGeneration
- type ConfigReloader
- func (cr *ConfigReloader) Generation() ConfigGeneration
- func (cr *ConfigReloader) OnReload(hook ReloadHook)
- func (cr *ConfigReloader) Reload(newCfg *Config) ReloadResult
- func (cr *ConfigReloader) Rollback() error
- func (cr *ConfigReloader) SetDrain(fn func(old *ConfigGeneration) error)
- func (cr *ConfigReloader) SetHealthCheck(fn func() error)
- func (cr *ConfigReloader) SetRollback(fn func(old *ConfigGeneration) error)
- func (cr *ConfigReloader) SetValidation(fn func(cfg *Config) error)
- type ContentTypeAwareCodec
- type Cookie
- type Ctx
- type DataPolicy
- type DefaultCtx
- func (c *DefaultCtx) AcceptCH(hints ...string)
- func (c *DefaultCtx) Accepts(offers ...string) string
- func (c *DefaultCtx) AcceptsCharsets(offers ...string) string
- func (c *DefaultCtx) AcceptsEncodings(offers ...string) string
- func (c *DefaultCtx) AcceptsLanguages(offers ...string) string
- func (c *DefaultCtx) AddBodyTransform(fn func([]byte) ([]byte, error))
- func (c *DefaultCtx) AllParams() map[string]string
- func (c *DefaultCtx) App() *App
- func (c *DefaultCtx) Append(key, value string)
- func (c *DefaultCtx) Attachment(filename string) Ctx
- func (c *DefaultCtx) Audit() AuditRecorder
- func (c *DefaultCtx) AutoETag() Ctx
- func (c *DefaultCtx) BaseURL() string
- func (c *DefaultCtx) Bind(v any) error
- func (c *DefaultCtx) BindForm(v any) error
- func (c *DefaultCtx) BindHeader(v any) error
- func (c *DefaultCtx) BindJSON(v any) error
- func (c *DefaultCtx) BindQuery(v any) error
- func (c *DefaultCtx) Body() []byte
- func (c *DefaultCtx) BodyCopy() []byte
- func (c *DefaultCtx) BodyParser(v any) error
- func (c *DefaultCtx) BodyRaw() []byte
- func (c *DefaultCtx) CaptureResponseBody()
- func (c *DefaultCtx) ClearCookie(name ...string)
- func (c *DefaultCtx) ClearSiteData(directives ...string)
- func (c *DefaultCtx) Compensate(fn func(context.Context) error)
- func (c *DefaultCtx) ConnectProtocol() string
- func (c *DefaultCtx) Context() context.Context
- func (c *DefaultCtx) CookieParser(v any) error
- func (c *DefaultCtx) CriticalCH(hints ...string)
- func (c *DefaultCtx) Deadline() (time.Time, bool)
- func (c *DefaultCtx) DelCookie(name string)
- func (c *DefaultCtx) DelResponseHeader(name string)
- func (c *DefaultCtx) Done() <-chan struct{}
- func (c *DefaultCtx) Download(filename string, downloadName ...string) error
- func (c *DefaultCtx) EarlyHint(uri string) bool
- func (c *DefaultCtx) EarlyHintsWithHeaders(uri string, attrs map[string]string) bool
- func (c *DefaultCtx) EchoBody(contentType ...string) error
- func (c *DefaultCtx) EchoJSON(validate ...bool) error
- func (c *DefaultCtx) Err() error
- func (c *DefaultCtx) ErrorReport(err error) ErrorReport
- func (c *DefaultCtx) ErrorResponse(err error) error
- func (c *DefaultCtx) File(filename string) error
- func (c *DefaultCtx) FirstCookie() string
- func (c *DefaultCtx) Flash(key string, value ...any) any
- func (c *DefaultCtx) FlashAll() map[string]any
- func (c *DefaultCtx) FormFile(field string) (*MultipartFile, error)
- func (c *DefaultCtx) Format(handlers map[string]HandlerFunc) error
- func (c *DefaultCtx) Fresh() bool
- func (c *DefaultCtx) Get(name string, defaults ...string) string
- func (c *DefaultCtx) GetCookie(name string) string
- func (c *DefaultCtx) GetHeaders() map[string][]string
- func (c *DefaultCtx) GetReqHeaders() map[string][]string
- func (c *DefaultCtx) GetRespHeader(name string, defaults ...string) string
- func (c *DefaultCtx) GetRespHeaders() map[string][]string
- func (c *DefaultCtx) HTML(s string) error
- func (c *DefaultCtx) HasResponseCookies() bool
- func (c *DefaultCtx) HeaderBytes(name []byte) []byte
- func (c *DefaultCtx) HeaderParser(v any) error
- func (c *DefaultCtx) Hijack(handler func(*ResponseConn) error) error
- func (c *DefaultCtx) Hostname() string
- func (c *DefaultCtx) IP() string
- func (c *DefaultCtx) IPs() []string
- func (c *DefaultCtx) IsFromLocal() bool
- func (c *DefaultCtx) IsXHR() bool
- func (c *DefaultCtx) JSON(v any) error
- func (c *DefaultCtx) JSONAppend(fn JSONAppendFunc) error
- func (c *DefaultCtx) JSONBytes(b []byte) error
- func (c *DefaultCtx) JSONP(data any, callback ...string) error
- func (c *DefaultCtx) JSONString(s string) error
- func (c *DefaultCtx) LastEventID() string
- func (c *DefaultCtx) Ledger(action, resource, resourceID string, before, after []byte) error
- func (c *DefaultCtx) Lifecycle() *RequestLifecycle
- func (c *DefaultCtx) Links(link ...string)
- func (c *DefaultCtx) Locals(key string, value ...any) any
- func (c *DefaultCtx) Location(path string)
- func (c *DefaultCtx) Method() string
- func (c *DefaultCtx) MethodBytes() []byte
- func (c *DefaultCtx) MultipartForm() (*MultipartForm, error)
- func (c *DefaultCtx) Next() error
- func (c *DefaultCtx) OnBeforeResponse(fn func(Ctx) error)
- func (c *DefaultCtx) OriginalURL() string
- func (c *DefaultCtx) OriginalURLBytes() []byte
- func (c *DefaultCtx) Param(name string) string
- func (c *DefaultCtx) Params(name string, defaults ...string) string
- func (c *DefaultCtx) ParamsInt(key string) (int, error)
- func (c *DefaultCtx) ParamsParser(v any) error
- func (c *DefaultCtx) Path() string
- func (c *DefaultCtx) PathBytes() []byte
- func (c *DefaultCtx) Problem(p Problem) error
- func (c *DefaultCtx) ProblemDetails(status int, title, detail, typeURI string) error
- func (c *DefaultCtx) Protocol() string
- func (c *DefaultCtx) Push(path string, method string, headers map[string]string) bool
- func (c *DefaultCtx) PushDocument(path string) bool
- func (c *DefaultCtx) PushFont(path string) bool
- func (c *DefaultCtx) PushImage(path string) bool
- func (c *DefaultCtx) PushResource(path string, method string, headers map[string]string) bool
- func (c *DefaultCtx) PushScript(path string) bool
- func (c *DefaultCtx) PushStylesheet(path string) bool
- func (c *DefaultCtx) Query(name string, def ...string) string
- func (c *DefaultCtx) QueryBool(key string, def ...bool) bool
- func (c *DefaultCtx) QueryBytes(name []byte) []byte
- func (c *DefaultCtx) QueryFloat(key string, def ...float64) float64
- func (c *DefaultCtx) QueryInt(key string, def ...int) int
- func (c *DefaultCtx) QueryMultiple(name string) []string
- func (c *DefaultCtx) QueryParser(v any) error
- func (c *DefaultCtx) Queue() Queue
- func (c *DefaultCtx) Range(size int64) ([]ByteRange, error)
- func (c *DefaultCtx) Redirect(location string, code ...int) error
- func (c *DefaultCtx) RedirectBack(fallback string, code ...int) error
- func (c *DefaultCtx) RedirectTo(name string, params map[string]string, code ...int) error
- func (c *DefaultCtx) RedirectWithFlash(location string, code int, flash map[string]any) error
- func (c *DefaultCtx) Reliability() *Reliability
- func (c *DefaultCtx) Render(name string, data any, layout ...string) error
- func (c *DefaultCtx) RequestHeader() *RequestHeader
- func (c *DefaultCtx) RequestPreference(name string) bool
- func (c *DefaultCtx) RequestPriority() HTTPPriority
- func (c *DefaultCtx) Responded() bool
- func (c *DefaultCtx) ResponseBody() []byte
- func (c *DefaultCtx) ResponseHeader(name string) string
- func (c *DefaultCtx) Rewrite(target string) error
- func (c *DefaultCtx) RunCompensations() error
- func (c *DefaultCtx) RunReliableEndpoint(policy ReliabilityPolicy, endpoint HandlerFunc) error
- func (c *DefaultCtx) SSE(fn func(*SSE) error) error
- func (c *DefaultCtx) SSEvent(event string, data any) error
- func (c *DefaultCtx) SafeErrorResponse(err error) error
- func (c *DefaultCtx) SaveFile(file *MultipartFile, dst string) error
- func (c *DefaultCtx) Secure() bool
- func (c *DefaultCtx) Send(b []byte) error
- func (c *DefaultCtx) Send103EarlyHints(links []string) bool
- func (c *DefaultCtx) SendBytes(b []byte) error
- func (c *DefaultCtx) SendContinue() error
- func (c *DefaultCtx) SendFile(filename string) error
- func (c *DefaultCtx) SendInformational(status int, headers map[string]string) bool
- func (c *DefaultCtx) SendStatus(code int) error
- func (c *DefaultCtx) SendStream(r io.Reader) error
- func (c *DefaultCtx) SendStreamLength(r io.Reader, size int64) error
- func (c *DefaultCtx) SendString(s string) error
- func (c *DefaultCtx) ServerInbox() *Inbox
- func (c *DefaultCtx) ServerOutbox() *Outbox
- func (c *DefaultCtx) Set(key, value string)
- func (c *DefaultCtx) SetAltSvc(value string) Ctx
- func (c *DefaultCtx) SetClientIP(value string)
- func (c *DefaultCtx) SetContext(ctx context.Context)
- func (c *DefaultCtx) SetCookie(cookie *Cookie)
- func (c *DefaultCtx) SetEnablePush(enabled bool)
- func (c *DefaultCtx) SetPreferenceApplied(value string) Ctx
- func (c *DefaultCtx) SetRequestBody(body []byte)
- func (c *DefaultCtx) SetResponsePriority(priority HTTPPriority) Ctx
- func (c *DefaultCtx) SetTrailer(key, value string)
- func (c *DefaultCtx) StaleWhileRevalidate(d time.Duration)
- func (c *DefaultCtx) Status(code int) Ctx
- func (c *DefaultCtx) StatusCode() int
- func (c *DefaultCtx) Stream(fn func(*StreamWriter) error) error
- func (c *DefaultCtx) StreamBody(fn func(io.Reader) error) error
- func (c *DefaultCtx) StreamLength(size int64, fn func(*StreamWriter) error) error
- func (c *DefaultCtx) Subdomains(offset ...int) []string
- func (c *DefaultCtx) Trailer(name string) string
- func (c *DefaultCtx) TransformBody(fn func([]byte) ([]byte, error))
- func (c *DefaultCtx) Type(mime string) Ctx
- func (c *DefaultCtx) Upgrade(protocol string, handler func(net.Conn) error) error
- func (c *DefaultCtx) Vary(fields ...string)
- func (c *DefaultCtx) XML(v any) error
- type DurableQueue
- func (q *DurableQueue) Close() error
- func (q *DurableQueue) DiscardFailed(ctx context.Context, id string) error
- func (q *DurableQueue) Enqueue(jobType string, payload any, headers ...map[string]string) (string, error)
- func (q *DurableQueue) EnqueueDelayed(jobType string, payload any, runAt time.Time, headers ...map[string]string) (string, error)
- func (q *DurableQueue) EnqueueJob(spec QueueJob, payload any, headers ...map[string]string) (string, error)
- func (q *DurableQueue) EnqueuePriority(jobType string, payload any, priority int, headers ...map[string]string) (string, error)
- func (q *DurableQueue) EnqueueWithKey(jobType string, payload any, concurrencyKey string, ...) (string, error)
- func (q *DurableQueue) ListJobs(ctx context.Context, state string, limit int) ([]QueueJobSnapshot, error)
- func (q *DurableQueue) PurgeJobs(ctx context.Context, state string, before time.Time, limit int) (int, error)
- func (q *DurableQueue) Recover() error
- func (q *DurableQueue) Register(jobType string, handler QueueHandler)
- func (q *DurableQueue) RetryFailed(ctx context.Context, id string) error
- func (q *DurableQueue) Start() error
- func (q *DurableQueue) Stats() (QueueStats, error)
- func (q *DurableQueue) Storage() QueueStorage
- type DurableQueueConfig
- type EncoderCodec
- type EndpointSelector
- type Environment
- type ErrorDefinition
- type ErrorHandler
- type ErrorKind
- type ErrorOptions
- type ErrorReport
- type ErrorSeverity
- type Extractor
- func BodyCSV(path string) Extractor[[]string]
- func BodyField(path string) Extractor[any]
- func BodyString(path string) Extractor[string]
- func FirstString(extractors ...Extractor[string]) Extractor[string]
- func FirstStrings(extractors ...Extractor[[]string]) Extractor[[]string]
- func HeaderCSV(name string) Extractor[[]string]
- func HeaderString(name string) Extractor[string]
- func LocalString(key string) Extractor[string]
- func ParamString(name string) Extractor[string]
- func PrincipalExtractor(ex PrincipalExtractors) Extractor[Principal]
- func PrincipalPermissionsExtractor() Extractor[[]string]
- func PrincipalRolesExtractor() Extractor[[]string]
- func PrincipalScopesExtractor() Extractor[[]string]
- func PrincipalTenantExtractor() Extractor[string]
- func QueryCSV(name string) Extractor[[]string]
- func QueryString(name string) Extractor[string]
- func StaticString(value string) Extractor[string]
- func StringFrom(ex Extractor[any]) Extractor[string]
- func StringsFrom(ex Extractor[any]) Extractor[[]string]
- func TenantExtractor(sources ...Extractor[string]) Extractor[string]
- type FieldError
- type FileAuditSink
- type FileQueueStorage
- func (s *FileQueueStorage) Claim(ctx context.Context, now time.Time) (*QueueJob, error)
- func (s *FileQueueStorage) Close() error
- func (s *FileQueueStorage) Complete(ctx context.Context, job *QueueJob) error
- func (s *FileQueueStorage) Dir() string
- func (s *FileQueueStorage) DiscardFailed(ctx context.Context, id string) error
- func (s *FileQueueStorage) Enqueue(ctx context.Context, job *QueueJob) error
- func (s *FileQueueStorage) Fail(ctx context.Context, job *QueueJob, cause error) error
- func (s *FileQueueStorage) ListJobs(ctx context.Context, state string, limit int) ([]QueueJobSnapshot, error)
- func (s *FileQueueStorage) PurgeJobs(ctx context.Context, state string, before time.Time, limit int) (int, error)
- func (s *FileQueueStorage) Recover(ctx context.Context) error
- func (s *FileQueueStorage) RequeueFailed(ctx context.Context, id string) error
- func (s *FileQueueStorage) Retry(ctx context.Context, job *QueueJob, cause error, backoff time.Duration) error
- func (s *FileQueueStorage) Stats(ctx context.Context) (QueueStats, error)
- type FileQueueStorageConfig
- type Form
- func (f Form) Bool(key string) (bool, error)
- func (f Form) First(key string) string
- func (f Form) Float64(key string) (float64, error)
- func (f Form) Int(key string) (int, error)
- func (f Form) Int64(key string) (int64, error)
- func (f Form) Strings(key string) []string
- func (f Form) Uint64(key string) (uint64, error)
- type FormBinder
- type FutureResponse
- type Group
- func (g *Group) All(path string, handlers ...HandlerFunc) *Group
- func (g *Group) AllTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Connect(path string, handlers ...HandlerFunc) *Group
- func (g *Group) ConnectTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Delete(path string, handlers ...HandlerFunc) *Group
- func (g *Group) DeleteTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Get(path string, handlers ...HandlerFunc) *Group
- func (g *Group) GetTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Group(prefix string, handlers ...HandlerFunc) *Group
- func (g *Group) Head(path string, handlers ...HandlerFunc) *Group
- func (g *Group) HeadTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Meta(key string, val any) *Group
- func (g *Group) Mount(prefix string, sub *App) *Group
- func (g *Group) Name(name string) *Group
- func (g *Group) Options(path string, handlers ...HandlerFunc) *Group
- func (g *Group) OptionsTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Patch(path string, handlers ...HandlerFunc) *Group
- func (g *Group) PatchTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Post(path string, handlers ...HandlerFunc) *Group
- func (g *Group) PostTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Purge(path string, handlers ...HandlerFunc) *Group
- func (g *Group) Put(path string, handlers ...HandlerFunc) *Group
- func (g *Group) PutTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Query(path string, handlers ...HandlerFunc) *Group
- func (g *Group) QueryTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Report(path string, handlers ...HandlerFunc) *Group
- func (g *Group) Search(path string, handlers ...HandlerFunc) *Group
- func (g *Group) Static(prefix, root string, config ...StaticConfig) *Group
- func (g *Group) StaticFS(prefix string, filesystem fs.FS, config ...StaticConfig) *Group
- func (g *Group) Tag(tags ...string) *Group
- func (g *Group) Trace(path string, handlers ...HandlerFunc) *Group
- func (g *Group) TraceTyped(path string, handler any, middleware ...HandlerFunc) *Group
- func (g *Group) Use(handlers ...HandlerFunc) *Group
- type HTTPError
- func BadRequest(message string) *HTTPError
- func Conflict(message string) *HTTPError
- func DependencyFailure(message string) *HTTPError
- func ErrorResponse(code, message string, status int) *HTTPError
- func Forbidden(message string) *HTTPError
- func InternalError(err error) *HTTPError
- func MethodNotAllowed(message string) *HTTPError
- func NewError(status int, message ...string) *HTTPError
- func NewHTTPError(status int, code, message string) *HTTPError
- func NotFound(message string) *HTTPError
- func PayloadTooLarge(message string) *HTTPError
- func PreconditionFailed(message string) *HTTPError
- func RateLimited(message string, retryAfter string) *HTTPError
- func Timeout(message string) *HTTPError
- func Unauthorized(message string) *HTTPError
- func Unavailable(message string) *HTTPError
- func UnsupportedMediaType(message string) *HTTPError
- func WrapHTTPError(err error, status int, code, message string) *HTTPError
- func (e *HTTPError) Error() string
- func (e *HTTPError) GoString() string
- func (e *HTTPError) Temporary() *HTTPError
- func (e *HTTPError) Unwrap() error
- func (e *HTTPError) WithCause(err error) *HTTPError
- func (e *HTTPError) WithDetails(details any) *HTTPError
- func (e *HTTPError) WithHeader(k, v string) *HTTPError
- func (e *HTTPError) WithMeta(k string, v any) *HTTPError
- type HTTPPriority
- type Handler
- type HandlerFunc
- func BudgetMiddleware(cfg BudgetConfig) HandlerFunc
- func ConfigGenerationMiddleware(reloader *ConfigReloader) HandlerFunc
- func DataClass(sensitivity string, categories ...string) HandlerFunc
- func MerkleAuditMiddleware(sink *MerkleAuditSink) HandlerFunc
- func RequireAuth() HandlerFunc
- func RequirePermission(permissions ...string) HandlerFunc
- func RequireRole(roles ...string) HandlerFunc
- func RequireScope(scopes ...string) HandlerFunc
- func RequireValues(ex Extractor[[]string], code, message, event string, required ...string) HandlerFunc
- func RouteSecurity(cfg RouteSecurityConfig) HandlerFunc
- func StaticJSON(body string) HandlerFunc
- func StaticJSONBytes(body []byte) HandlerFunc
- func StaticText(body string) HandlerFunc
- func TenantResolver(header string, required bool) HandlerFunc
- func TenantResolverWith(ex Extractor[string], required bool) HandlerFunc
- func TypedDelete[Res any](fn func(Ctx) (Res, error)) HandlerFunc
- func TypedGet[Res any](fn func(Ctx) (Res, error)) HandlerFunc
- func TypedHandler[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc
- func TypedPatch[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc
- func TypedPost[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc
- func TypedPut[Req any, Res any](fn func(Ctx, Req) (Res, error)) HandlerFunc
- func TypedStream[Res any](fn func(Ctx) (Res, io.Reader, error)) HandlerFunc
- func UsePrincipal(ex Extractor[Principal], required ...bool) HandlerFunc
- func ValidateHeaders(v any, cfg ...ValidateConfig) HandlerFunc
- func ValidateMiddleware(factory func() Validator, cfg ...ValidateConfig) HandlerFunc
- func ValidateQuery(v any, cfg ...ValidateConfig) HandlerFunc
- type HashChainAuditSink
- type Header
- type HealthCheckResult
- type HealthConfig
- type HealthProbe
- type HealthResponse
- type HookFunc
- type Hooks
- type IdempotencyDecision
- type IdempotencyJanitor
- type IdempotencyRecord
- type IdempotencyRepository
- type IdempotencyStore
- func (s *IdempotencyStore) Begin(key, reqHash, method, path string) (IdempotencyDecision, *IdempotencyRecord, error)
- func (s *IdempotencyStore) Close() error
- func (s *IdempotencyStore) Complete(key, reqHash string, status int, contentType string, ...) error
- func (s *IdempotencyStore) Path() string
- func (s *IdempotencyStore) PurgeExpired(ctx context.Context, now time.Time) (int, error)
- type Inbox
- type InboxEvent
- type InboxMessage
- type InboxStore
- type JSONAppendFunc
- type JSONAppender
- type JSONDecoder
- type JSONDecoderConfigurer
- type JSONEncoder
- type JSONEncoderConfigurer
- type JSONEngine
- type JSONEngineFuncSet
- type JSONField
- type JSONMarshaler
- type JSONRawMessage
- type JSONSchema
- type JSONStreamingDecoder
- type JSONUnmarshaler
- type JSONValue
- type KernelBackend
- type KernelCapabilities
- type KernelConfig
- type KernelProfile
- type KernelReadinessIssue
- type KernelReadinessReport
- type KernelReadinessSeverity
- type KernelRuntimeInfo
- type LedgerEntry
- type LifecycleState
- type LogAdapter
- type Logger
- type MaintenanceReport
- type Map
- type MemoryHTTPCache
- type MemoryOutboxInboxStore
- func (s *MemoryOutboxInboxStore) BeginInbox(ctx context.Context, m InboxMessage) (bool, error)
- func (s *MemoryOutboxInboxStore) ClaimOutbox(ctx context.Context, now time.Time, limit int) ([]*OutboxMessage, error)
- func (s *MemoryOutboxInboxStore) Close() error
- func (s *MemoryOutboxInboxStore) CompleteOutbox(ctx context.Context, id string) error
- func (s *MemoryOutboxInboxStore) FailOutbox(ctx context.Context, id string, err error) error
- func (s *MemoryOutboxInboxStore) ListOutbox(ctx context.Context, state string, limit int) ([]OutboxMessage, error)
- func (s *MemoryOutboxInboxStore) RetryOutbox(ctx context.Context, id string, err error, delay time.Duration) error
- func (s *MemoryOutboxInboxStore) SaveOutbox(ctx context.Context, m *OutboxMessage) error
- type MerkleAuditSink
- type MerkleCheckpoint
- type MerkleConfig
- type Meta
- type MethodNotAllowedHandler
- type Mode
- type MultipartBinder
- type MultipartFile
- type MultipartForm
- type NopClientMetrics
- type NotFoundHandler
- type OCSPStapler
- type OpenAPIConfig
- type Option
- func WithAllowedHosts(hosts ...string) Option
- func WithBaseContext(fn func(net.Listener) context.Context) Option
- func WithCaptureResponseBody(enabled bool) Option
- func WithCompliance(cc ComplianceConfig) Option
- func WithComplianceEndpointAuth(middleware ...HandlerFunc) Option
- func WithConnContext(fn func(context.Context, net.Conn) context.Context) Option
- func WithContentSecurityPolicy(policy string) Option
- func WithDebug(enabled bool) Option
- func WithDisableH2C(disabled bool) Option
- func WithDisableHTTP2(disabled bool) Option
- func WithDisableKeepAlive(disabled bool) Option
- func WithDisablePanicRecovery(disabled bool) Option
- func WithEnvironment(env Environment) Option
- func WithErrorHandler(h ErrorHandler) Option
- func WithErrorOptions(eo ErrorOptions) Option
- func WithHTTP2IdleTimeout(d time.Duration) Option
- func WithHandlerTimeout(d time.Duration) Option
- func WithIdleTimeout(d time.Duration) Option
- func WithKernel(cfg KernelConfig) Option
- func WithKernelDefaults() Option
- func WithLogger(l Logger) Option
- func WithMaxConcurrentStreams(n uint32) Option
- func WithMaxConnections(n int) Option
- func WithMaxConnectionsPerIP(n int) Option
- func WithMaxGoroutines(n int) Option
- func WithMaxHeaderCount(n int) Option
- func WithMaxHeaderListSize(n int) Option
- func WithMaxHeapBytes(n uint64) Option
- func WithMaxInFlightRequests(n int64) Option
- func WithMaxRequestBodySize(n int) Option
- func WithMaxRequestLineSize(n int) Option
- func WithMethodNotAllowedHandler(h MethodNotAllowedHandler) Option
- func WithMode(mode Mode) Option
- func WithNotFoundHandler(h NotFoundHandler) Option
- func WithOptionsHandler(h OptionsHandler) Option
- func WithReadBufferSize(n int) Option
- func WithReadHeaderTimeout(d time.Duration) Option
- func WithReadTimeout(d time.Duration) Option
- func WithReliability(r ReliabilityConfig) Option
- func WithRequestBodyTimeout(d time.Duration) Option
- func WithRequestHeadHandler(h HandlerFunc) Option
- func WithResourceCheckInterval(d time.Duration) Option
- func WithSafeParams(enabled bool) Option
- func WithSecureByDefault(enabled bool) Option
- func WithSendDateHeader(enabled bool) Option
- func WithSendKeepAliveHeader(enabled bool) Option
- func WithServerHeader(header string) Option
- func WithSharedState(provider SharedStateProvider) Option
- func WithShutdownTimeout(d time.Duration) Option
- func WithStartupBanner(cfg StartupBannerConfig) Option
- func WithStartupBannerColor(enabled bool) Option
- func WithStartupBannerDisabled(disabled bool) Option
- func WithStartupBannerName(name string) Option
- func WithStartupBannerOutput(w io.Writer) Option
- func WithStartupBannerSubtitle(subtitle string) Option
- func WithStartupBannerVersion(version string) Option
- func WithStreamRequestBody(enabled bool) Option
- func WithTLSHandshakeTimeout(d time.Duration) Option
- func WithTemplateEngine(te TemplateEngine) Option
- func WithWriteBufferSize(n int) Option
- func WithWriteTimeout(d time.Duration) Option
- type OptionsHandler
- type Outbox
- type OutboxConfig
- type OutboxDispatcher
- type OutboxEvent
- type OutboxMessage
- type OutboxStore
- type PanicError
- type Param
- type PreforkConfig
- type PreforkOption
- type Principal
- type PrincipalExtractors
- type Problem
- type ProblemDetailsPayload
- type ProxyProtocolConfig
- type ProxyProtocolListener
- type PushPromise
- type Queue
- type QueueEvent
- type QueueFailedOperator
- type QueueHandler
- type QueueJanitor
- type QueueJob
- type QueueJobLister
- type QueueJobSnapshot
- type QueueStats
- type QueueStorage
- type REFEngine
- type RedactionConfig
- type RedactionMode
- type Redactor
- type RedirectPolicy
- type Reliability
- func (r *Reliability) ApplyPolicy(c Ctx, p ReliabilityPolicy) error
- func (r *Reliability) BeginTx(ctx context.Context) (ReliabilityTx, error)
- func (r *Reliability) Close() error
- func (r *Reliability) Compact(ctx context.Context) (MaintenanceReport, error)
- func (r *Reliability) IdempotencyStore() IdempotencyRepository
- func (r *Reliability) Inbox() *Inbox
- func (r *Reliability) Journal() RequestJournalStore
- func (r *Reliability) Middleware() HandlerFunc
- func (r *Reliability) Outbox() *Outbox
- func (r *Reliability) PurgeExpiredIdempotency(ctx context.Context, now time.Time) (int, error)
- func (r *Reliability) Queue() *DurableQueue
- func (r *Reliability) Repair(ctx context.Context) error
- func (r *Reliability) Start() error
- type ReliabilityConfig
- type ReliabilityPolicy
- type ReliabilityTx
- type ReloadHook
- type ReloadResult
- type Request
- func (r *Request) AddHeader(k, v string) *Request
- func (r *Request) Body(v any) *Request
- func (r *Request) BodyLimit(n int64) *Request
- func (r *Request) Bytes(b []byte, ct ...string) *Request
- func (r *Request) Connect(ctx context.Context, u string) (*Response, error)
- func (r *Request) Cookie(c *http.Cookie) *Request
- func (r *Request) Decode(v any) *Request
- func (r *Request) DecodeError(v any) *Request
- func (r *Request) Delete(ctx context.Context, u string) (*Response, error)
- func (r *Request) Do(ctx context.Context, method, rawurl string) (*Response, error)
- func (r *Request) Form(values url.Values) *Request
- func (r *Request) Get(ctx context.Context, u string) (*Response, error)
- func (r *Request) Head(ctx context.Context, u string) (*Response, error)
- func (r *Request) Header(k, v string) *Request
- func (r *Request) Headers(h map[string]string) *Request
- func (r *Request) IdempotencyKey(k string) *Request
- func (r *Request) JSON(v any) *Request
- func (r *Request) Meta(k string, v any) *Request
- func (r *Request) Method(ctx context.Context, method, u string) (*Response, error)
- func (r *Request) Multipart(fields map[string]string, files ...UploadFile) *Request
- func (r *Request) Options(ctx context.Context, u string) (*Response, error)
- func (r *Request) Param(k, v string) *Request
- func (r *Request) Patch(ctx context.Context, u string) (*Response, error)
- func (r *Request) Post(ctx context.Context, u string) (*Response, error)
- func (r *Request) Put(ctx context.Context, u string) (*Response, error)
- func (r *Request) Query(k, v string) *Request
- func (r *Request) QueryMap(values map[string]string) *Request
- func (r *Request) QueryRaw(raw string) *Request
- func (r *Request) QuerySet(k, v string) *Request
- func (r *Request) QueryValues(values url.Values) *Request
- func (r *Request) Reader(rd io.Reader, ct ...string) *Request
- func (r *Request) ResponseLimit(n int64) *Request
- func (r *Request) Retry(p RetryPolicy) *Request
- func (r *Request) Send(ctx context.Context, method, u string) (*Response, error)
- func (r *Request) Stream() *Request
- func (r *Request) String(s string, ct ...string) *Request
- func (r *Request) Timeout(d time.Duration) *Request
- func (r *Request) Trace(ctx context.Context, u string) (*Response, error)
- func (r *Request) Use(m ...ClientMiddleware) *Request
- type RequestHeader
- func (h *RequestHeader) Add(name, value string)
- func (h *RequestHeader) Del(name string)
- func (h *RequestHeader) Get(name string, defaults ...string) string
- func (h *RequestHeader) GetHeaders() map[string][]string
- func (h *RequestHeader) Init()
- func (h *RequestHeader) Peek(name []byte) []byte
- func (h *RequestHeader) PeekStr(name string) string
- func (h *RequestHeader) Set(name, value string)
- func (h *RequestHeader) SetCookie(c *DefaultCtx, name, value string)
- func (h *RequestHeader) Values(name string) []string
- type RequestJournal
- type RequestJournalEntry
- type RequestJournalStore
- type RequestLifecycle
- type ResettableCodec
- type Response
- func (r *Response) Bytes() ([]byte, error)
- func (r *Response) Close() error
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Decode(v any) error
- func (r *Response) DownloadTo(w io.Writer) (int64, error)
- func (r *Response) DrainAndClose() error
- func (r *Response) Header() http.Header
- func (r *Response) IsError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) Reader() io.ReadCloser
- func (r *Response) Save(path string, perm os.FileMode) error
- func (r *Response) SaveAtomic(path string, perm os.FileMode) error
- func (r *Response) StatusCode() int
- func (r *Response) String() (string, error)
- type ResponseConn
- type RetryPolicy
- type RoundRobinSelector
- type RouteInfo
- type RoutePattern
- type RouteSecurityConfig
- type Router
- func (r *Router) Add(method, path string, h HandlerFunc)
- func (r *Router) AddNamed(method, path, name string, h HandlerFunc)
- func (r *Router) Allowed(path []byte) []string
- func (r *Router) Find(method, path string, params *[]Param) HandlerFunc
- func (r *Router) FindBytes(method, path []byte, params *[]Param) HandlerFunc
- func (r *Router) FindPrebuiltResponseBytes(method, path []byte) []byte
- func (r *Router) Freeze()
- func (r *Router) Methods() []string
- func (r *Router) Name(method, path, name string)
- func (r *Router) URL(name string, values ...map[string]string) (string, error)
- func (r *Router) URLWithQuery(name string, params map[string]any, query map[string]any) (string, error)
- type RuntimeInfo
- type SLO
- type SLOSnapshot
- type SLOTracker
- func (t *SLOTracker) BurnRate(route string) float64
- func (t *SLOTracker) GetState(route string) (SLOSnapshot, bool)
- func (t *SLOTracker) Handler() HandlerFunc
- func (t *SLOTracker) IsCompliant(route string) bool
- func (t *SLOTracker) Match(path string) (route string, ok bool)
- func (t *SLOTracker) RecordRequest(route string, latency time.Duration, failed bool)
- func (t *SLOTracker) Register(pattern string, slo SLO)
- func (t *SLOTracker) Snapshot() map[string]SLOSnapshot
- func (t *SLOTracker) Stop()
- func (t *SLOTracker) Unregister(pattern string) bool
- type SLOTrackerConfig
- type SSE
- func (s *SSE) Comment(comment string) error
- func (s *SSE) Context() context.Context
- func (s *SSE) Done() <-chan struct{}
- func (s *SSE) Ping() error
- func (s *SSE) Send(data any) error
- func (s *SSE) SendEvent(event string, data any) error
- func (s *SSE) SetRetry(d time.Duration) error
- func (s *SSE) WriteEvent(ev SSEEvent) error
- type SSEEvent
- type SafeConfig
- type SameSite
- type SecureEnvelope
- type SecurityEvent
- type SecurityEventSink
- type SecurityEventStream
- type SecurityFinding
- type ServerMetrics
- type ServerTLSOptions
- type ServiceClient
- func (s *ServiceClient) Connect(ctx context.Context, p string) (*Response, error)
- func (s *ServiceClient) Delete(ctx context.Context, p string) (*Response, error)
- func (s *ServiceClient) Do(ctx context.Context, method, p string, body ...any) (*Response, error)
- func (s *ServiceClient) Get(ctx context.Context, p string) (*Response, error)
- func (s *ServiceClient) Head(ctx context.Context, p string) (*Response, error)
- func (s *ServiceClient) Header(k, v string) *ServiceClient
- func (s *ServiceClient) Options(ctx context.Context, p string) (*Response, error)
- func (s *ServiceClient) Patch(ctx context.Context, p string, body any) (*Response, error)
- func (s *ServiceClient) Post(ctx context.Context, p string, body any) (*Response, error)
- func (s *ServiceClient) Put(ctx context.Context, p string, body any) (*Response, error)
- func (s *ServiceClient) Query(ctx context.Context, p string, body any) (*Response, error)
- func (s *ServiceClient) R() *Request
- func (s *ServiceClient) Search(ctx context.Context, p string, body any) (*Response, error)
- func (s *ServiceClient) Trace(ctx context.Context, p string) (*Response, error)
- func (s *ServiceClient) Use(m ...ClientMiddleware) *ServiceClient
- type SharedStateProvider
- type StartupBannerConfig
- type StartupBannerData
- type StartupBannerLine
- type StaticConfig
- type StoredOutbox
- func (o *StoredOutbox) DispatchOnce(ctx context.Context, limit int) (int, error)
- func (o *StoredOutbox) List(ctx context.Context, state string, limit int) ([]OutboxMessage, error)
- func (o *StoredOutbox) Publish(ctx context.Context, topic string, payload any, headers map[string]string) (string, error)
- type StreamWriter
- type StructuredError
- type TemplateEngine
- type TokenSource
- type TokenSourceFunc
- type TypedResponse
- type UploadFile
- type ValidateConfig
- type ValidationError
- type ValidationErrorBuilder
- func (b *ValidationErrorBuilder) Add(field, code, message string)
- func (b *ValidationErrorBuilder) Addf(field, code, format string, args ...any)
- func (b *ValidationErrorBuilder) Clear()
- func (b *ValidationErrorBuilder) Error() *ValidationError
- func (b *ValidationErrorBuilder) HasErrors() bool
- func (b *ValidationErrorBuilder) ValidationErrors() ValidationErrors
- type ValidationErrors
- type ValidationRule
- type Validator
- type XDPConfig
- type XDPManager
- type XDPMode
Constants ¶
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 ────────────────────────────────────────────────
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 ──────────────────────────────────────────────────────────────────────
const ( HeaderSecFetchDest = "Sec-Fetch-Dest" HeaderSecFetchMode = "Sec-Fetch-Mode" HeaderSecFetchSite = "Sec-Fetch-Site" HeaderSecFetchUser = "Sec-Fetch-User" )
── Fetch metadata ────────────────────────────────────────────────────────────
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 ──────────────────────────────────────────────────────────────
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 ────────────────────────────────────────────────────────
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 ─────────────────────────────────────────────────────────
const ( HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" )
── WebSocket ─────────────────────────────────────────────────────────────────
const ( HeaderHTTP2Settings = "HTTP2-Settings" HeaderAltUsed = "Alt-Used" HeaderConnectionID = "Connection-ID" )
── HTTP/2 / HTTP/3 ──────────────────────────────────────────────────────────
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 ──────────────────────────────────────────────────────
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 ──────────────────────────────────────────────────────────────
const ( HTTP09 = "HTTP/0.9" HTTP10 = "HTTP/1.0" HTTP11 = "HTTP/1.1" HTTP2 = "HTTP/2" HTTP3 = "HTTP/3" )
── Protocol versions ─────────────────────────────────────────────────────────
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 ───────────────────────────────────────────────────────────
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 ─────────────────────────────────────────
const ( CharsetUTF8 = "utf-8" CharsetUTF16 = "utf-16" CharsetISO88591 = "iso-8859-1" CharsetUSASCII = "us-ascii" )
── Charset names ─────────────────────────────────────────────────────────────
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 ──────────────────────────────────────────────────
const ( CookieSameSiteStrict = "Strict" CookieSameSiteLax = "Lax" CookieSameSiteNone = "None" )
── SameSite cookie values ────────────────────────────────────────────────────
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 ────────────────────────────────────────────────────
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.
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" )
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 )
const ( HeaderRequestID = "X-Request-ID" HeaderIdempotencyKey = "Idempotency-Key" HeaderReplayed = "X-Idempotency-Replayed" )
const ( PriorityLow = -10 PriorityNormal = 0 PriorityHigh = 10 )
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 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 StatusInternalServerError = 500 StatusNotImplemented = 501 StatusBadGateway = 502 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 StatusVariantAlsoNegotiates = 506 StatusInsufficientStorage = 507 StatusLoopDetected = 508 StatusNotExtended = 510 StatusNetworkAuthenticationRequired = 511 )
── Status codes ──────────────────────────────────────────────────────────────
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" 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" StatusTextInternalServerError = "Internal Server Error" StatusTextNotImplemented = "Not Implemented" StatusTextBadGateway = "Bad Gateway" 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 ¶
var ( ErrInvalidChunkedBody = errors.New("invalid chunked request body") ErrBodyTooLarge = errors.New("request body too large") )
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) )
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) )
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) )
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) )
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) )
var ( HeaderReportToBytes = []byte(HeaderReportTo) HeaderReportingEndpointsBytes = []byte(HeaderReportingEndpoints) )
var ( ErrBadRequest = NewHTTPError(StatusBadRequest, "BAD_REQUEST", "Bad Request") 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") 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
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") )
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") )
var ( ErrRouteNotFound = errors.New("fh: named route not found") ErrRouteParamMissing = errors.New("fh: required route parameter missing") )
var ( ErrInvalidUpgrade = errors.New("invalid connection upgrade request") ErrHijackHTTP2 = errors.New("connection hijacking is unavailable on HTTP/2 streams") )
var DefaultStaticConfig = StaticConfig{
Index: "index.html",
MaxRanges: defaultMaxStaticRanges,
}
DefaultStaticConfig is the default configuration for Static and StaticFS.
var ErrAppAlreadyStarted = errors.New("fh: app has already been started")
var ErrDuplicateInboxMessage = errors.New("fh: duplicate inbox message")
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.
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.
var (
ErrInvalidBindTarget = errors.New("fh: bind target must be a non-nil pointer")
)
var ErrInvalidCookie = errors.New("fh: invalid cookie")
var ErrMalformedRequest = errors.New("malformed HTTP request")
ErrMalformedRequest is returned when the request cannot be parsed.
var ErrQueueEmpty = errors.New("fh: queue empty")
var ErrRequestLineTooLarge = errors.New("request line too large")
ErrRequestLineTooLarge is returned when the request line exceeds the limit.
var ErrRewrite = errors.New("fh: reroute rewritten request")
ErrSharedStateUnavailable is returned when an App has no shared-state provider configured.
var ErrXDPUnsupported = kernel.ErrXDPUnsupported
var JSONTypeCache sync.Map // map[reflect.Type][]JSONField
Functions ¶
func AppendHeader ¶
AppendHeader appends "Key: Value\r\n" to dst — zero alloc with sufficient capacity.
func AppendHeaderBytes ¶
AppendHeaderBytes appends "Key: Value\r\n" to dst for byte slices.
func AppendJSONString ¶
AppendJSONString appends s as a complete quoted JSON string.
func AppendJSONStringContent ¶
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 ¶
AppendJSONStringContentBytes appends b escaped for JSON string content without allocation.
func AtomicHandoff ¶
func Bind ¶
Bind parses request body, query params, and headers into target struct v based on struct tags.
func BindCookie ¶
BindCookie parses cookies into target struct v based on `cookie:"name"` tags.
func BindHeader ¶
BindHeader parses request headers into target struct v based on `header:"Header-Name"` tags.
func BindParams ¶
BindParams parses named route parameters into target struct v based on `params:"name"` tags.
func BindQuery ¶
BindQuery parses URL query string parameters into target struct v based on `query:"key"` tags.
func BytesEqualFold ¶
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 DecodeBody ¶
DecodeBody decodes data using the registered codec for contentType.
func DecodeForm ¶
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 DeleteResponseHeader ¶
DeleteResponseHeader removes a response header when the concrete context supports mutation. It keeps the public Ctx interface stable for adapters.
func DeterministicIdempotencyKey ¶
DeterministicIdempotencyKey creates a stable key from deterministic parts.
func EncodeBody ¶
EncodeBody encodes v using a registered encoder codec.
func HasHeaderToken ¶
func InboxDedupeKey ¶
func JSONMarshal ¶
JSONMarshal is a convenience wrapper over the active JSON engine with the same direct-path behavior as jsonCodec.Marshal.
func JSONUnmarshal ¶
JSONUnmarshal is a convenience wrapper over the active JSON engine with the same UseNumber/default strict single-document behavior as jsonCodec.Unmarshal.
func MustSetJSONEngine ¶
func MustSetJSONEngine(engine JSONEngine)
MustSetJSONEngine is the panic-on-error variant for process startup.
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 ¶
ParseCookie parses a Cookie request header value into a name-value map.
func ProblemDetails ¶
ProblemDetails sends an RFC 9457 / RFC 7807 application/problem+json error response.
func RedactSecret ¶
func RedactSecrets ¶
RedactSecrets removes common secret-bearing values from debug strings.
func RedactValue ¶
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 ¶
RegisterCodecAlias registers another content type for an existing codec.
func RegisterCodecStrict ¶
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 ¶
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 SSEvent ¶
SSEvent sends a standalone Server-Sent Event (SSE) to the client with proper headers.
func SetClientIP ¶
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 SignCookie ¶
func StatusReason ¶
StatusReason returns the standard reason phrase for code. It returns an empty string for unknown status codes.
func StreamJSON ¶
StreamJSON streams a JSON response without buffering the entire body. Useful for large datasets or real-time data.
func StreamNDJSON ¶
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 ValidToken ¶
func ValidateStruct ¶
ValidateStruct validates a struct using its "validate" struct tags. It returns a *ValidationError with field-level details, or nil if valid.
func ValidateStructWith ¶
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 WithBudget ¶
WithBudget stores the budget in the request context.
func WithTLSState ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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) 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) ConnectTyped ¶
func (a *App) ConnectTyped(path string, handler any, middleware ...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 (*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 ¶
EnableSwaggerUI mounts an embedded interactive Swagger UI documentation viewer at prefix and live OpenAPI spec at prefix/openapi.json.
func (*App) ErrorCount ¶
ErrorCount returns the number of errors rendered for a stable error code.
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) 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) IsDraining ¶
func (*App) KernelReadiness ¶
func (a *App) KernelReadiness() KernelReadinessReport
func (*App) KernelRuntimeInfo ¶
func (a *App) KernelRuntimeInfo() KernelRuntimeInfo
func (*App) ListenAutoTLS ¶
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 ¶
ListenAutoTLSWithGracefulShutdown is the graceful-shutdown counterpart to ListenAutoTLS, draining on SIGINT/SIGTERM exactly like ListenTLSWithGracefulShutdown.
func (*App) ListenContext ¶
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) ListenTLSContext ¶
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 ¶
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 ¶
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 ¶
ListenUnixContext is the context-aware Unix-domain socket counterpart to ListenContext.
func (*App) ListenWithGracefulShutdown ¶
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 ¶
Logger returns the application logger so middleware and integrations can emit structured messages without reaching into App internals.
func (*App) Metrics ¶
func (a *App) Metrics() ServerMetrics
Metrics returns a real-time snapshot of server runtime metrics.
func (*App) Mount ¶
Mount mounts a sub-App onto a path prefix, registering all sub-routes, handlers, tags, and metadata.
func (*App) MustStateStore ¶
MustStateStore is the initialization-oriented form of StateStore. It panics when shared state is unavailable or the namespace cannot be opened.
func (*App) Name ¶
Name names the most recently registered route, allowing fluent usage such as app.Get("/users/:id", handler).Name("users.show").
func (*App) OnShutdown ¶
func (*App) OpenAPISpec ¶
OpenAPISpec generates an OpenAPI 3.0 specification map from all registered routes.
func (*App) OptionsTyped ¶
func (a *App) OptionsTyped(path string, handler any, middleware ...HandlerFunc) *App
func (*App) PatchTyped ¶
func (a *App) PatchTyped(path string, handler any, middleware ...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) PutTyped ¶
func (a *App) PutTyped(path string, handler any, middleware ...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) Reliability ¶
func (a *App) Reliability() *Reliability
Reliability returns the configured reliability runtime, if enabled.
func (*App) Reload ¶
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 ¶
RouteTreeString returns an ASCII list representation of registered routes.
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) ServeContext ¶
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) SetREF ¶ added in v0.0.26
SetREF sets the Runtime Execution Fabric (REF) engine on the App.
func (*App) StateStore ¶
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 ¶
StaticFS registers a GET route that serves files from an fs.FS (embed.FS, etc.).
func (*App) Test ¶
Test executes a standard *http.Request directly against app in-memory over net.Pipe() without binding TCP ports.
func (*App) TraceTyped ¶
func (a *App) TraceTyped(path string, handler any, middleware ...HandlerFunc) *App
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 (*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 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
}
type AuditSinkCloser ¶
type BatchResult ¶
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 ¶
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) CanUpstream ¶
CanUpstream reports whether the budget allows another upstream call.
func (*Budget) CheckBodySize ¶
CheckBodySize reports whether the body size fits the budget.
func (*Budget) CheckMemory ¶
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) Remaining ¶
Remaining returns the time remaining until the budget deadline. If no deadline is set, it returns the maximum duration.
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 ¶
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) R ¶
R returns a reusable fluent request builder. Do not use the returned Request concurrently.
func (*Client) Service ¶
func (c *Client) Service(base string) *ServiceClient
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 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 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
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) Inflight ¶
func (m *ClientStatsMetrics) Inflight(d int64)
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
// 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:
- Parse new configuration.
- Validate routes and policies.
- Compile routing structures.
- Load certificates and keys.
- Initialize dependencies.
- Run health checks.
- Swap the complete configuration atomically.
- Drain resources belonging to the old revision.
- 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:
- Parse the new configuration.
- Validate routes and policies.
- Compile routing structures.
- Load certificates and keys.
- Initialize dependencies.
- Run health checks.
- Swap the complete configuration atomically.
- Drain resources belonging to the old revision.
- 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 ¶
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 ¶
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.
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) 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 (*DefaultCtx) Links ¶
func (c *DefaultCtx) Links(link ...string)
Links joins the given URIs into a Link response header field (RFC 8288).
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 ¶
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 ¶
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) 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) 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 ¶
RedirectTo redirects to a named route. Route parameters are substituted and additional values become query parameters.
func (*DefaultCtx) RedirectWithFlash ¶
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) 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 ¶
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) EnqueueDelayed ¶
func (*DurableQueue) EnqueueJob ¶
func (*DurableQueue) EnqueuePriority ¶
func (*DurableQueue) EnqueueWithKey ¶
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) 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 EncoderCodec ¶
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 ¶
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" 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 ¶
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 BodyString ¶
func HeaderCSV ¶
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 ¶
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 ParamString ¶
func PrincipalExtractor ¶
func PrincipalExtractor(ex PrincipalExtractors) Extractor[Principal]
PrincipalExtractor returns a reusable extractor for a Principal composed from field extractors.
func PrincipalRolesExtractor ¶
func QueryString ¶
func StaticString ¶
func TenantExtractor ¶
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 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) 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) ListJobs ¶
func (s *FileQueueStorage) ListJobs(ctx context.Context, state string, limit int) ([]QueueJobSnapshot, error)
func (*FileQueueStorage) RequeueFailed ¶
func (s *FileQueueStorage) RequeueFailed(ctx context.Context, id string) error
func (*FileQueueStorage) Stats ¶
func (s *FileQueueStorage) Stats(ctx context.Context) (QueueStats, error)
type FileQueueStorageConfig ¶
FileQueueStorage is the default file/directory based QueueStorage.
type Form ¶
Form is the decoded representation of application/x-www-form-urlencoded. Values stores exact repeated-key values. Tree stores bracket-notation nesting.
type FormBinder ¶
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.
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) AllTyped ¶
func (g *Group) AllTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) ConnectTyped ¶
func (g *Group) ConnectTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) DeleteTyped ¶
func (g *Group) DeleteTyped(path string, handler any, middleware ...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) HeadTyped ¶
func (g *Group) HeadTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) Meta ¶
Meta attaches key-value metadata to the most recently registered route in this group.
func (*Group) OptionsTyped ¶
func (g *Group) OptionsTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) PatchTyped ¶
func (g *Group) PatchTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) PostTyped ¶
func (g *Group) PostTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) PutTyped ¶
func (g *Group) PutTyped(path string, handler any, middleware ...HandlerFunc) *Group
func (*Group) QueryTyped ¶
func (g *Group) QueryTyped(path string, handler any, middleware ...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 ¶
StaticFS registers a GET route that serves files from an fs.FS (embed.FS, etc.).
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 DependencyFailure ¶
func ErrorResponse ¶
ErrorResponse creates a typed error response.
func InternalError ¶
func MethodNotAllowed ¶
func NewError ¶
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 ¶
NewHTTPError constructs a client-safe typed error.
func PayloadTooLarge ¶
func PreconditionFailed ¶
func RateLimited ¶
func Unauthorized ¶
func Unavailable ¶
func UnsupportedMediaType ¶
func WrapHTTPError ¶
WrapHTTPError attaches a private cause to a client-safe typed error.
func (*HTTPError) WithDetails ¶
func (*HTTPError) WithHeader ¶
type HTTPPriority ¶
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 ¶
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 ¶
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 ¶
Header is a single HTTP header key/value. Both slices point into the read buffer — zero copy.
type HealthCheckResult ¶
type HealthConfig ¶
type HealthConfig struct {
Probes map[string]HealthProbe
}
type HealthProbe ¶
type HealthProbe func() bool
type HealthResponse ¶
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 ¶
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) Path ¶
func (s *IdempotencyStore) Path() string
func (*IdempotencyStore) PurgeExpired ¶
type InboxEvent ¶
type InboxMessage ¶
type InboxStore ¶
type JSONAppendFunc ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) NewDecoder ¶
func (e JSONEngineFuncSet) NewDecoder(r io.Reader) JSONDecoder
func (JSONEngineFuncSet) NewEncoder ¶
func (e JSONEngineFuncSet) NewEncoder(w io.Writer) JSONEncoder
func (JSONEngineFuncSet) Valid ¶
func (e JSONEngineFuncSet) Valid(data []byte) bool
type JSONMarshaler ¶
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 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 ¶
JSONUnmarshaler is compatible with encoding/json.Unmarshaler and high-performance JSON engines that honor UnmarshalJSON.
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 ¶
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 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 (*MemoryOutboxInboxStore) ListOutbox ¶
func (s *MemoryOutboxInboxStore) ListOutbox(ctx context.Context, state string, limit int) ([]OutboxMessage, error)
func (*MemoryOutboxInboxStore) RetryOutbox ¶
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 ¶
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) Inflight ¶
func (NopClientMetrics) Inflight(int64)
type NotFoundHandler ¶
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 ¶
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 WithCaptureResponseBody ¶
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 WithDisableH2C ¶
func WithDisableHTTP2 ¶
func WithDisableKeepAlive ¶
func WithEnvironment ¶
func WithEnvironment(env Environment) Option
func WithErrorHandler ¶
func WithErrorHandler(h ErrorHandler) Option
func WithErrorOptions ¶
func WithErrorOptions(eo ErrorOptions) Option
func WithHTTP2IdleTimeout ¶
func WithHandlerTimeout ¶
func WithIdleTimeout ¶
func WithKernel ¶
func WithKernel(cfg KernelConfig) Option
func WithKernelDefaults ¶
func WithKernelDefaults() Option
func WithLogger ¶
func WithMaxConnections ¶
func WithMaxConnectionsPerIP ¶
func WithMaxGoroutines ¶
func WithMaxHeaderCount ¶
func WithMaxHeaderListSize ¶
func WithMaxHeapBytes ¶
func WithMaxInFlightRequests ¶
func WithMaxRequestBodySize ¶
func WithMaxRequestLineSize ¶
func WithMethodNotAllowedHandler ¶
func WithMethodNotAllowedHandler(h MethodNotAllowedHandler) Option
func WithMode ¶
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 WithReadHeaderTimeout ¶
func WithReadTimeout ¶
func WithReliability ¶
func WithReliability(r ReliabilityConfig) Option
func WithRequestBodyTimeout ¶
func WithRequestHeadHandler ¶
func WithRequestHeadHandler(h HandlerFunc) Option
func WithSafeParams ¶
func WithSecureByDefault ¶
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 WithSendKeepAliveHeader ¶
func WithServerHeader ¶
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 WithStartupBanner ¶
func WithStartupBanner(cfg StartupBannerConfig) Option
WithStartupBanner replaces the whole startup banner configuration.
func WithStartupBannerColor ¶
WithStartupBannerColor enables/disables ANSI color in the startup banner.
func WithStartupBannerDisabled ¶
WithStartupBannerDisabled enables/disables the startup banner. Passing true disables it.
func WithStartupBannerName ¶
WithStartupBannerName sets the displayed application/framework name.
func WithStartupBannerOutput ¶
WithStartupBannerOutput sets the destination for the startup banner.
func WithStartupBannerSubtitle ¶
WithStartupBannerSubtitle sets the displayed subtitle.
func WithStartupBannerVersion ¶
WithStartupBannerVersion sets the displayed version string.
func WithStreamRequestBody ¶
func WithTLSHandshakeTimeout ¶
func WithTemplateEngine ¶
func WithTemplateEngine(te TemplateEngine) Option
func WithWriteBufferSize ¶
func WithWriteTimeout ¶
type OptionsHandler ¶
OptionsHandler handles automatic OPTIONS responses for matched routes and server-wide OPTIONS * requests. allowed is already ordered for the Allow header.
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 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 ¶
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 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 ¶
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 ¶
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 ¶
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.
type PushPromise ¶
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 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 QueueJanitor ¶
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 ¶
func DefaultRedactor ¶
func DefaultRedactor() *Redactor
func NewRedactor ¶
func NewRedactor(cfg RedactionConfig) *Redactor
func (*Redactor) RedactHeaders ¶
func (*Redactor) RedactString ¶
type RedirectPolicy ¶
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 ¶
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) 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) DecodeError ¶
func (*Request) IdempotencyKey ¶
func (*Request) Multipart ¶
func (r *Request) Multipart(fields map[string]string, files ...UploadFile) *Request
func (*Request) ResponseLimit ¶
func (*Request) Retry ¶
func (r *Request) Retry(p RetryPolicy) *Request
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 (j *RequestJournal) Append(e RequestJournalEntry) error
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) DownloadTo ¶
DownloadTo streams a response body to a writer without buffering it all in memory.
func (*Response) DrainAndClose ¶
func (*Response) Reader ¶
func (r *Response) Reader() io.ReadCloser
func (*Response) SaveAtomic ¶
SaveAtomic writes a response to path through a temporary file and atomic rename.
func (*Response) StatusCode ¶
type ResponseConn ¶
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)
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 (*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 ¶
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) FindBytes ¶
func (r *Router) FindBytes(method, path []byte, params *[]Param) HandlerFunc
func (*Router) FindPrebuiltResponseBytes ¶
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.
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) 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 ¶
Comment sends a comment line (ignored by client JavaScript EventSource, useful for heartbeats/pings).
func (*SSE) 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 ¶
Ping sends an empty comment ping (`: ping\n\n`) to keep the connection alive through proxy timeouts.
func (*SSE) Send ¶
Send sends data with no custom event type (defaults to standard "message" event).
func (*SSE) WriteEvent ¶
WriteEvent formats and sends a single SSE event frame to the stream.
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 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 (s *SecurityEventStream) Emit(e SecurityEvent)
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) Header ¶
func (s *ServiceClient) Header(k, v string) *ServiceClient
func (*ServiceClient) R ¶
func (s *ServiceClient) R() *Request
func (*ServiceClient) Use ¶
func (s *ServiceClient) Use(m ...ClientMiddleware) *ServiceClient
type SharedStateProvider ¶
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 ¶
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 (*StoredOutbox) List ¶
func (o *StoredOutbox) List(ctx context.Context, state string, limit int) ([]OutboxMessage, 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
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 ¶
TokenSource supplies bearer tokens without binding the client to any OAuth package.
type TokenSourceFunc ¶
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 ¶
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 ¶
func (b *ValidationErrorBuilder) Error() *ValidationError
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 XDPManager ¶
type XDPManager = kernel.XDPManager
func NewXDPManager ¶
func NewXDPManager(cfg XDPConfig) *XDPManager
Source Files
¶
- app.go
- audit.go
- banner.go
- binder.go
- budget.go
- chunked.go
- client_ip.go
- codec.go
- compliance.go
- configreload.go
- conn.go
- constants.go
- cookie.go
- ctx.go
- errors.go
- etag.go
- files.go
- fs.go
- group.go
- hardening.go
- header.go
- health.go
- http2.go
- http2_connect.go
- http2_push.go
- httpclient.go
- httpclient_ext.go
- json.go
- logger.go
- merkle_audit.go
- metrics.go
- native_transport.go
- openapi.go
- outbox_inbox.go
- policy.go
- pool.go
- prefer.go
- prefork.go
- prefork_unix.go
- principal.go
- priority.go
- problem.go
- proxyprotocol.go
- redaction.go
- reliability.go
- reliability_ext.go
- request_body.go
- request_stream.go
- response_header.go
- route_security.go
- route_typed.go
- router.go
- runtime.go
- serve_common.go
- shared_state.go
- slo.go
- sse.go
- status.go
- stream.go
- swagger.go
- template.go
- test_client.go
- tls_acme.go
- tls_config.go
- tls_state.go
- typed.go
- unix_listener.go
- utils.go
- validate.go
- websocket.go
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
|