web

package
v2.0.0-beta.6 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 21 Imported by: 0

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

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 Module

func Module(opts ...ModOpt) kernel.Component

Module returns the http component for chok.Use.

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.

func POST

func POST[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], opts ...handler.HandleOption)

POST registers a typed POST endpoint.

func PUT

func PUT[T any, R any](r kernel.Router, pattern string, fn handler.HandlerFunc[T, R], opts ...handler.HandleOption)

PUT registers a typed PUT 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

func (c *Component) BoundAddr() string

BoundAddr returns the actual listen address once Serve is up ("" before) — fixtures bind :0 and discover the port here.

func (*Component) Close

func (c *Component) Close(ctx context.Context) error

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

func (c *Component) Init(ctx context.Context, k kernel.Kernel) error

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

func (c *Component) ProvideRouter() kernel.Router

ProvideRouter implements kernel.RouterProvider: this module fills the single router-provider role for the mount phase.

func (*Component) Routes

func (c *Component) Routes() []Route

Routes exposes the route table (registration order) — swagger's data source.

func (*Component) Serve

func (c *Component) Serve(ctx context.Context, ready func()) error

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

type HandlerMeta interface {
	Meta() handler.Meta
}

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.

func (*Options) Validate

func (o *Options) Validate() error

Validate implements conf.Validatable.

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

Wrap returns w as a ResponseWriter, wrapping once — writers that already track state pass through unchanged.

type Route

type Route struct {
	Method  string
	Pattern string // full pattern including group prefixes
	Meta    *handler.Meta
}

Route is one route-table entry, in registration order. Meta is nil for plain handlers (health endpoints, user http.HandlerFunc values).

Jump to

Keyboard shortcuts

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