Documentation
¶
Overview ¶
Package web is the chok v2 HTTP layer: a stdlib http.Server plus a ServeMux-backed implementation of the kernel Router/RouterProvider contracts (SPEC §4). The module owns the default middleware stack — RED metrics and the dedicated access log included — wiring soft dependencies (metrics, tracing, authz) by role, never by import.
Index ¶
- func DELETE[T any](r kernel.Router, pattern string, fn handler.ActionFunc[T], ...)
- func GET[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], ...)
- func Module(opts ...ModOpt) kernel.Component
- func PATCH[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], ...)
- func POST[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], ...)
- func PUT[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], ...)
- type Component
- func (c *Component) AttachErrorMappers(reg *apierr.MapperRegistry)
- func (c *Component) BoundAddr() string
- func (c *Component) Close(ctx context.Context) error
- func (c *Component) Describe() kernel.Descriptor
- func (c *Component) Init(ctx context.Context, k kernel.Kernel) error
- func (c *Component) ProvideRouter() kernel.Router
- func (c *Component) Routes() []Route
- func (c *Component) Serve(ctx context.Context, ready func()) error
- type HandlerMeta
- type ModOpt
- type Options
- type ResponseWriter
- type Route
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DELETE ¶
func DELETE[T any](r kernel.Router, pattern string, fn handler.ActionFunc[T], opts ...handler.HandleOption)
DELETE registers a typed DELETE action (no response body, 204 by default — override with handler.WithSuccessCode).
func GET ¶
func GET[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], opts ...handler.HandleOption)
GET registers a typed GET endpoint.
func PATCH ¶
func PATCH[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], opts ...handler.HandleOption)
PATCH registers a typed PATCH endpoint.
Types ¶
type Component ¶
type Component struct {
// contains filtered or unexported fields
}
Component is the http module. Exported so peers can reach the route table: swagger does
webc, ok := chok.Get[*web.Component](k, "http")
for _, rt := range webc.Routes() { ... }
func (*Component) AttachErrorMappers ¶
func (c *Component) AttachErrorMappers(reg *apierr.MapperRegistry)
AttachErrorMappers receives the per-App mapper registry during App assembly (structural handshake, mini-SPEC §5) — the WithErrorMapper injection point moved here from the v1 gin mount hook (SPEC §9).
func (*Component) BoundAddr ¶
BoundAddr returns the actual listen address once Serve is up ("" before) — fixtures bind :0 and discover the port here.
func (*Component) Close ¶
Close releases the dedicated access logger (when one was built). The server itself has already stopped: the draining phase waits for Serve to return before any Close runs.
func (*Component) Describe ¶
func (c *Component) Describe() kernel.Descriptor
Describe implements kernel.Component. Kind is "http" — the module name is an implementation detail, the capability is not (SPEC §6).
func (*Component) Init ¶
Init decodes the section and assembles the request pipeline. Soft dependencies initialized before us (declared in Needs) are looked up by role interface; each absent one simply drops its middleware — no error, no stub (M2 acceptance: "absent ⇒ not mounted, no error").
func (*Component) ProvideRouter ¶
ProvideRouter implements kernel.RouterProvider: this module fills the single router-provider role for the mount phase.
func (*Component) Routes ¶
Routes exposes the route table (registration order) — swagger's data source.
func (*Component) Serve ¶
Serve implements kernel.Server: bind, signal readiness, serve until ctx cancels, then drain gracefully within shutdown_timeout and force-Close whatever outlives it — hung handlers must not outlive registry teardown (v1 Stop contract). Serve returns only after the wind-down completes, so every dependency is still alive while in-flight requests finish (SPEC §3.3 draining).
type HandlerMeta ¶
HandlerMeta is the optional interface a registered http.Handler may implement to contribute route metadata (request/response types, summary, tags) to the route table. handler.HandleRequest / HandleAction / HandleList construct such handlers; the router type-asserts at registration — metadata stays a web-layer concern, the kernel.Router contract does not grow (SPEC §4.2 item 1).
type ModOpt ¶
type ModOpt func(*Component)
ModOpt configures the module at assembly time.
func WithMiddleware ¶
func WithMiddleware(mw ...kernel.Middleware) ModOpt
WithMiddleware appends user middleware after the default stack (Recovery → RequestID → ClientIP → [Tracing] → Logger → [Timeout] → [Metrics] → [AccessLog] → [AttachAuthz] → [error mappers]), just before the router.
type Options ¶
type Options struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Addr string `mapstructure:"addr" default:":8080" reload:"restart"`
ReadTimeout time.Duration `mapstructure:"read_timeout" default:"30s" reload:"restart"`
WriteTimeout time.Duration `mapstructure:"write_timeout" default:"30s" reload:"restart"`
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" default:"10s" reload:"restart"`
IdleTimeout time.Duration `mapstructure:"idle_timeout" default:"120s" reload:"restart"`
// RequestTimeout, when positive, adds the Timeout middleware:
// the request context is cancelled and a 504 envelope written if
// the handler produced nothing in time. Zero disables (default).
RequestTimeout time.Duration `mapstructure:"request_timeout" reload:"restart"`
// ShutdownTimeout bounds the graceful Shutdown on stop; when
// in-flight requests outlive it, the server force-Closes so hung
// handlers can't outlive registry teardown (v2 addition — the v1
// server borrowed the App's stop context, but the kernel Serve
// contract carries a cancellation signal, not a deadline).
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" default:"10s" reload:"restart"`
// DrainDelay is the pause between readiness flipping to 503
// (draining phase) and Serve contexts being cancelled. The App
// inherits it into the kernel draining phase unless WithDrainDelay
// was set explicitly (SPEC §9; default 5s, zero disables).
DrainDelay time.Duration `mapstructure:"drain_delay" default:"5s" reload:"restart"`
// TrustedProxies is the list of CIDRs / IPs whose X-Forwarded-For
// and X-Real-IP headers the ClientIP resolver may honour. Empty
// (the default) trusts NO proxy — the client IP is the direct
// socket peer. Set to ["127.0.0.1"] behind a local reverse proxy,
// ["10.0.0.0/8"] behind an in-cluster LB, etc.
//
// Not setting this means the account login limiter's IP-keyed
// bucket would be bypassable by any client spoofing
// X-Forwarded-For; the fail-closed default avoids that trap.
TrustedProxies []string `mapstructure:"trusted_proxies" reload:"restart"`
// H2C enables cleartext HTTP/2 (v2 addition): gRPC-style clients
// and in-cluster meshes can speak h2 without TLS termination.
H2C bool `mapstructure:"h2c" default:"false" reload:"restart"`
}
Options is the "http" yaml section (the v1 section shape carried over; h2c and shutdown_timeout are v2 additions). Everything here shapes server construction, so every field is restart-only — the framework reload diff warns on changes without dispatching.
type ResponseWriter ¶
type ResponseWriter interface {
http.ResponseWriter
// Status returns the response code sent so far; 200 when the
// handler wrote a body without an explicit WriteHeader, and also
// 200 before anything was written (net/http's implicit default).
Status() int
// Written reports whether any part of the response (status line or
// body bytes) has gone out.
Written() bool
// BytesWritten counts body bytes written so far.
BytesWritten() int64
// Unwrap exposes the underlying writer for http.ResponseController
// (Flush / SetWriteDeadline / Hijack all resolve through it).
Unwrap() http.ResponseWriter
}
ResponseWriter is the written-tracking writer the server installs at the outermost layer of every request (SPEC §4.2 item 2). It backs the three "no double write" contracts — handler.WriteResponse, middleware.Recovery and middleware.Timeout all consult Written() (via structural assertion, so neither package imports web).
func Wrap ¶
func Wrap(w http.ResponseWriter) ResponseWriter
Wrap returns w as a ResponseWriter, wrapping once — writers that already track state pass through unchanged.