Documentation
¶
Overview ¶
Package server is pleme-io's inbound-serving Go primitive (BOREALIS §2.7, codename kyuu): a thin, uniform layer over the standard library's net/http for every akeyless service that receives requests — webhook receivers, MCP servers, custom producers, connectivity tooling.
It is borealis-style by construction:
- Composition over framework (Law 2). The handler is a stdlib http.Handler and a http.ServeMux; every middleware stage is a plain func(http.Handler) http.Handler. server-go owns NONE of your handlers — it wraps the universal interface of HTTP serving and gets out of the way.
- The canonical middleware order is BAKED IN (recover → request-log → RED metrics → http.TimeoutHandler → throttle → optional auth → your handler), because middleware order is a correctness property, not a style choice (BOREALIS §2.7).
- Config via shikumi (Law 3). Config is a typed yaml struct; FromConfig consumes the already-loaded sub-struct and never calls shikumi.Load.
- Health has a single owner (Law 1, Law 8). server-go contributes ZERO health semantics: it mounts lifecycle-go's three health planes (/livez|/healthz|/readyz|/startupz) and metrics-go's /metrics on its mux, but lifecycle-go owns the semantics. The lifecycle spine (graceful drain, readiness flip, ordered shutdown) is lifecycle-go's lifecycle.App.
Connect-on-one-port (connectrpc.com/connect) is the import-gated half (Law 6): the core carries no Connect dependency. The server-go/connect leaf mounts a Connect handler on the SAME mux/port — Connect handlers ARE http.Handler, so they share the one mux and the one middleware chain (BOREALIS §2.7).
srv, _ := server.New(server.Config{Addr: ":8080"},
server.WithLogger(log),
server.WithMetrics(mx),
server.WithHandler("GET /v1/foo", fooHandler),
)
app, _ := lifecycle.New(cfg.Lifecycle, lifecycle.WithLogger(log),
lifecycle.WithMetricsHandler(mx.Handler()))
srv.Register(app) // server registers as a lifecycle component
return app.Run(ctx) // graceful drain on ctx cancel
Index ¶
- Constants
- type Authenticator
- type AuthenticatorFunc
- type Config
- type Middleware
- type Option
- func WithAuth(a Authenticator) Option
- func WithHandler(pattern string, h http.Handler) Option
- func WithHandlerFunc(pattern string, h func(http.ResponseWriter, *http.Request)) Option
- func WithLogger(log *slog.Logger) Option
- func WithMetrics(mx *metrics.Registry) Option
- func WithMiddleware(mw ...Middleware) Option
- type Server
- func (s *Server) Addr() string
- func (s *Server) Config() Config
- func (s *Server) Handle(pattern string, h http.Handler)
- func (s *Server) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request))
- func (s *Server) Handler() http.Handler
- func (s *Server) MountHealth(reg *lifecycle.Registry)
- func (s *Server) MountMetrics()
- func (s *Server) Mux() *http.ServeMux
- func (s *Server) Register(app *lifecycle.App) *lifecycle.App
- type TLSConfig
- type ThrottleConfig
Constants ¶
const ( // DefaultAddr is the listen address when [Config].Addr is empty. DefaultAddr = ":8080" // DefaultReadTimeout bounds reading the whole request when unset. DefaultReadTimeout = 15 * time.Second // DefaultReadHeaderTimeout bounds reading request headers when unset — the // primary slowloris control. DefaultReadHeaderTimeout = 5 * time.Second // DefaultWriteTimeout bounds writing the response when unset. DefaultWriteTimeout = 30 * time.Second // DefaultIdleTimeout bounds keep-alive idle time when unset. DefaultIdleTimeout = 60 * time.Second // DefaultHandlerTimeout is the per-request http.TimeoutHandler deadline when // unset. A negative [Config].HandlerTimeout disables the stage entirely. DefaultHandlerTimeout = 30 * time.Second // DefaultMaxHeaderBytes is the request-header cap when unset (1 MiB). DefaultMaxHeaderBytes = 1 << 20 // DefaultThrottleRPS is the steady-state rate when the throttle is enabled // with RPS == 0. DefaultThrottleRPS = 100.0 // DefaultThrottleBurst is the burst depth when the throttle is enabled with // Burst == 0. DefaultThrottleBurst = 50 )
Fleet defaults for the Config knobs. Exported so a consumer can reference the exact value the zero Config resolves to.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Authenticator ¶
type Authenticator interface {
// Authenticate inspects the request and returns nil to admit it, or an error
// to reject it with 401 Unauthorized. The error's message is not written to
// the response body (it may carry internal detail); only the status is.
Authenticate(r *http.Request) error
}
Authenticator is the optional auth gate's contract (BOREALIS §2.7 — the auth stage is OPTIONAL and travels as one Middleware like every other stage, Law 2). It decides per request whether to admit the caller, returning a non-nil error to reject with 401. It is deliberately a small behaviour-carrier interface (Law 5): the akeyless auth gate (built on auth-go's AuthResolver / *auth.Session) satisfies it without server-go importing the SDK, and a test or third party can supply any gate — server-go owns the HTTP wiring of the decision, never the decision itself.
type AuthenticatorFunc ¶
AuthenticatorFunc adapts an ordinary func into an Authenticator (the http.HandlerFunc pattern).
func (AuthenticatorFunc) Authenticate ¶
func (f AuthenticatorFunc) Authenticate(r *http.Request) error
Authenticate satisfies Authenticator.
type Config ¶
type Config struct {
// Addr is the TCP listen address (e.g. ":8080", "127.0.0.1:0"). Empty means
// [DefaultAddr] (":8080"). The Connect handler (server-go/connect) and the
// REST/health/metrics handlers all share this one port — Connect handlers
// ARE http.Handler, so they mount on the same mux (BOREALIS §2.7).
Addr string `yaml:"addr" json:"addr"`
// ReadTimeout bounds reading the entire request, header + body. Zero means
// [DefaultReadTimeout]. It is the first slowloris control (an attacker that
// dribbles a request body is cut at this deadline).
ReadTimeout time.Duration `yaml:"read_timeout" json:"read_timeout"`
// ReadHeaderTimeout bounds reading just the request headers. Zero means
// [DefaultReadHeaderTimeout]. Separated from ReadTimeout so a streaming-body
// or long-poll handler can keep a generous body deadline while still capping
// header dribble (the slowloris vector).
ReadHeaderTimeout time.Duration `yaml:"read_header_timeout" json:"read_header_timeout"`
// WriteTimeout bounds writing the response. Zero means [DefaultWriteTimeout].
// Set it to 0 explicitly via the option layer for streaming responses; the
// yaml zero takes the default, so streaming services tune it up.
WriteTimeout time.Duration `yaml:"write_timeout" json:"write_timeout"`
// IdleTimeout bounds how long a keep-alive connection may stay idle before
// the server closes it. Zero means [DefaultIdleTimeout].
IdleTimeout time.Duration `yaml:"idle_timeout" json:"idle_timeout"`
// HandlerTimeout is the per-request deadline enforced by the baked
// http.TimeoutHandler middleware stage (BOREALIS §2.7). Zero means
// [DefaultHandlerTimeout]; a negative value disables the stage (no timeout
// handler is installed). It bounds unbounded handler runtime independently of
// the connection-level Read/Write timeouts.
HandlerTimeout time.Duration `yaml:"handler_timeout" json:"handler_timeout"`
// MaxHeaderBytes caps the size of request headers. Zero means
// [DefaultMaxHeaderBytes] (1 MiB, the net/http default made explicit).
MaxHeaderBytes int `yaml:"max_header_bytes" json:"max_header_bytes"`
// Throttle configures the inbound x/time/rate limiter — the unbounded-
// concurrency control paired with HandlerTimeout's slowloris control.
Throttle ThrottleConfig `yaml:"throttle" json:"throttle"`
// TLS configures optional TLS termination. When empty, the server listens
// plaintext (TLS is normally terminated at an ingress in front of the pod).
TLS TLSConfig `yaml:"tls" json:"tls"`
}
Config is the typed, yaml-tagged runtime policy of a Server — the BOREALIS Law 3 config surface. It is loaded once at main through shikumi-go (defaults → env → file, file wins) and the sub-struct is handed to FromConfig; the constructors here NEVER call shikumi.Load themselves (BOREALIS §3.5). A zero Config is valid: New/FromConfig fill every field with a sane default.
The caller's shikumi-loaded root config embeds it:
type Root struct {
Server server.Config `yaml:"server"`
// …
}
and hands cfg.Server to FromConfig. Precedence (args > env > file) is resolved by shikumi during the load, not here.
type Middleware ¶
Middleware is the universal middleware contract: a decorator that wraps one http.Handler and returns another (BOREALIS Law 2 — composition over framework; the chi/stdlib `func(http.Handler) http.Handler` shape). Every stage in the baked chain is one of these, and a caller's own stages (WithMiddleware) compose into the same chain unchanged.
type Option ¶
type Option func(*Server)
Option configures a Server at construction, the functional-options half of the canonical `New(cfg, opts…)` shape (BOREALIS §3.5).
func WithAuth ¶
func WithAuth(a Authenticator) Option
WithAuth installs the optional auth gate (BOREALIS §2.7). The Authenticator is run as the innermost baked stage and rejects with 401 on a non-nil decision. The akeyless gate (built on auth-go's resolver / *auth.Session) satisfies Authenticator without server-go importing the SDK. A nil authenticator leaves the gate off (pass-through).
func WithHandler ¶
WithHandler registers a handler for a http.ServeMux pattern (Go 1.22+ method+wildcard patterns, e.g. "GET /v1/foo", "POST /v1/bar/{id}"). It is the REST authoring verb; the handler is wrapped by the baked chain at Register time. Repeated calls register multiple routes. A nil handler is ignored.
func WithHandlerFunc ¶
WithHandlerFunc is WithHandler for a bare http.HandlerFunc.
func WithLogger ¶
WithLogger sets the slog logger threaded through the request-log and recover middleware stages. It is logging-go's *slog.Logger (the fleet lingua franca); server-go never owns a log format. The default is a no-op logger (slog.DiscardHandler) so an unconfigured server is silent, not noisy.
func WithMetrics ¶
WithMetrics installs metrics-go's metrics.Registry so the RED middleware stage feeds it and Server.Register/Server.MountMetrics mounts its /metrics handler on the shared mux. A nil registry leaves the RED stage a pass-through and mounts nothing (the chain shape is unchanged). This is the SAME registry the lifecycle owner receives via lifecycle.WithMetricsHandler — one instrumentation surface (BOREALIS §2.5a).
func WithMiddleware ¶
func WithMiddleware(mw ...Middleware) Option
WithMiddleware appends caller-supplied Middleware stages, applied AFTER the baked chain and BEFORE the user handler (so they wrap the handler but are wrapped by recover/log/metrics/timeout/throttle/auth). They compose into the one func(http.Handler) http.Handler contract (Law 2). nil stages are skipped.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the inbound HTTP serving primitive (BOREALIS §2.7). It owns a http.ServeMux, the baked middleware chain, an http.Server, and the wiring that mounts lifecycle-go's health planes + metrics-go's /metrics on the same mux/port. It does NOT own a lifecycle of its own — Server.Register hands its listener/shutdown to a lifecycle.App, the single owner of the run loop and the graceful-shutdown choreography (Law 1, Law 8).
The zero value is not usable; construct with New or FromConfig. A Server is safe to configure (WithHandler/WithMount) before Server.Register; the handler tree is frozen at Register time.
func FromConfig ¶
FromConfig constructs a Server from an already-loaded Config sub-struct, plus functional [Option]s. It is the canonical config-consuming constructor (BOREALIS §3.5 `pkg.FromConfig(cfg pkg.Config) (*T, error)`) and MUST NOT itself call shikumi.Load — the loader runs once at main, and a server-go/cfg leaf (or the caller's root) is the shikumi adapter that produces the Config this takes. FromConfig and New share one body so there is one construction path.
func New ¶
New constructs a Server from a Config plus functional [Option]s, the canonical `pkg.New(required…, opts ...Option) (*T, error)` shape (BOREALIS §3.5). A zero Config is valid and yields sane defaults. New never itself loads config from disk — the loader lives once at main via shikumi (Law 3); use FromConfig to consume an already-loaded sub-struct (they share one body).
func (*Server) Addr ¶
Addr returns the bound listener address once Server.Register's actor has started listening (useful in tests with ":0"). It returns the configured Addr before the listener binds.
func (*Server) Handle ¶
Handle registers a handler on the shared mux after construction (the post-New form of WithHandler).
func (*Server) HandleFunc ¶
HandleFunc registers a handler func on the shared mux after construction.
func (*Server) Handler ¶
Handler returns the fully-wrapped http.Handler: the shared mux with the canonical baked middleware chain applied in order (BOREALIS §2.7):
recover → request-log → RED metrics → http.TimeoutHandler → throttle → (optional) auth → [caller middleware] → mux
recover is OUTERMOST so it catches panics from every other stage; request-log and RED metrics see every request (including 401s and 429s) so they are observable; the timeout/throttle stages bound runtime and concurrency; the optional auth gate is innermost of the baked stages. The mounted health and metrics endpoints are served on a PRE-CHAIN branch in [Server.rootHandler] so a probe answers and a scraper exposes without passing through auth/throttle/ RED (the selector-skip-auth-on-health concern, BOREALIS §2.7).
func (*Server) MountHealth ¶
MountHealth records lifecycle-go's three health planes (the lifecycle.Registry handler: /livez, /healthz, /readyz, /startupz) to be served OUTSIDE the baked middleware chain so a probe answers even under auth/throttle (the selector-skip-auth-on-health concern). The actual routing happens in [Server.rootHandler] on a pre-chain branch. It is idempotent. lifecycle-go owns the health SEMANTICS; server-go owns only this HTTP routing of them (Law 1, Law 8). Server.Register calls it automatically with the app's registry.
func (*Server) MountMetrics ¶
func (s *Server) MountMetrics()
MountMetrics records metrics-go's /metrics exposition to be served OUTSIDE the baked chain (a scraper must not be rate-limited or RED-counted), routed pre-chain in [Server.rootHandler]. It uses the registry's own metrics.Registry.Path. It is idempotent and a no-op when no metrics registry was installed via WithMetrics. Server.Register calls it automatically.
func (*Server) Mux ¶
Mux returns the shared http.ServeMux. It is the seam the import-gated server-go/connect leaf uses to mount a Connect handler on the SAME port (Connect handlers ARE http.Handler), and how a caller registers routes after construction. Routes registered here are wrapped by the baked chain at Server.Register/Server.Handler time, EXCEPT the mounted health/metrics endpoints, which are mounted to bypass auth/throttle (a probe must answer even when the gate would reject — the selector-skip-auth-on-health concern).
func (*Server) Register ¶
Register wires this server into a lifecycle.App as a lifecycle component (BOREALIS §2.7): it mounts the app's health planes and the metrics /metrics on the shared mux, then registers the listen/serve loop as a lifecycle ACTOR (the oklog/run shape, because net.Listener.Accept cannot watch a context) with a graceful-shutdown interrupt. lifecycle.App owns the run loop and the K8s choreography: on ctx cancel (signal) it flips readiness DOWN, drains, then interrupts this actor, which calls http.Server.Shutdown to drain in-flight requests gracefully within the app's ShutdownGrace budget.
Register MUST be called before lifecycle.App.Run. After Register the handler tree is frozen. It returns the App for chaining.
type TLSConfig ¶
type TLSConfig struct {
// CertFile is the PEM certificate (chain) path. Empty disables TLS.
CertFile string `yaml:"cert_file" json:"cert_file,omitempty"`
// KeyFile is the PEM private-key path. Empty disables TLS.
KeyFile string `yaml:"key_file" json:"key_file,omitempty"`
}
TLSConfig configures optional TLS termination at the server. When both CertFile and KeyFile are set the server serves HTTPS; otherwise it serves plaintext.
type ThrottleConfig ¶
type ThrottleConfig struct {
// Enabled toggles the throttle stage. The pointer distinguishes an absent
// field (nil → disabled) from an explicit `enabled: true`. Disabled is the
// default: a primitive does not throttle unless asked (composition over
// framework — the limiter is a stage you opt into, not a policy imposed).
Enabled *bool `yaml:"enabled" json:"enabled"`
// RPS is the steady-state requests-per-second allowed across all inbound
// requests (the token-bucket refill rate). Zero with Enabled set means
// [DefaultThrottleRPS].
RPS float64 `yaml:"rps" json:"rps"`
// Burst is the maximum burst above RPS the bucket absorbs. Zero with Enabled
// set means [DefaultThrottleBurst].
Burst int `yaml:"burst" json:"burst"`
}
ThrottleConfig configures the inbound rate limiter (the throttle middleware stage, BOREALIS §2.7). Backed by golang.org/x/time/rate's token bucket: RPS is the steady-state refill rate, Burst the bucket depth.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admission is server-go's import-gated Kubernetes admission-webhook leaf (BOREALIS §2.7, registry §4a — server-go/admission; NET/SEC).
|
Package admission is server-go's import-gated Kubernetes admission-webhook leaf (BOREALIS §2.7, registry §4a — server-go/admission; NET/SEC). |
|
Package connect is server-go's import-gated Connect-on-one-port leaf (BOREALIS §2.7, Law 6).
|
Package connect is server-go's import-gated Connect-on-one-port leaf (BOREALIS §2.7, Law 6). |
|
Package grpc is server-go's import-gated gRPC-serving leaf (BOREALIS §2.7, Law 6; registry §4a — server-go/grpc, NET).
|
Package grpc is server-go's import-gated gRPC-serving leaf (BOREALIS §2.7, Law 6; registry §4a — server-go/grpc, NET). |
|
Package grpcauth is server-go's import-gated gRPC auth-interceptor leaf (BOREALIS §2.7, Law 6; registry §4a — grpc-auth-interceptor, A6, NET/CFG-09).
|
Package grpcauth is server-go's import-gated gRPC auth-interceptor leaf (BOREALIS §2.7, Law 6; registry §4a — grpc-auth-interceptor, A6, NET/CFG-09). |