This is the fast way to orient yourself in Servekit's public API.
It covers the full exported surface of the servekit package and the version subpackage.
Go doc comments remain the canonical symbol-level reference. This file is the companion view that groups the exported surface by the decisions you make when using the package.
If you only remember the common path, remember this:
New(...)creates the server with Servekit's baseline already installedHandle(...)is the normal route shape for request in, payload/error outRun(...)listens, mounts the built-in operational endpoints, manages readiness, and shuts down cleanly
Everything else in this file exists to customize that path without abandoning net/http.
-
ServerThe main service object. It owns route registration, built-in middleware, readiness state, transport settings, and the default operational endpoints.
-
New(...)Creates a server with Servekit's production-oriented baseline: JSON success and error encoding, panic recovery, request and correlation IDs, access logs, OpenTelemetry, built-in
GET /livez,GET /readyz, andGET /version, plus conservativehttp.Servertimeouts and a default request body limit. -
OptionServer-wide configuration hook applied in order during
New(...).
-
Handle(...)Registers the normal Servekit route shape. Use this when the endpoint wants to inspect the request, do application work, and return one payload or one error.
-
HandlerFuncStructured handler function used by
Handle(...).Shape:
func(*http.Request) (any, error) -
ResponseEncoderSuccess encoder used by
Handle(...).Shape:
func(http.ResponseWriter, *http.Request, any) error -
ErrorEncoderError encoder used by
Handle(...).Shape:
func(http.ResponseWriter, *http.Request, error) error -
JSONResponse()Default success encoder.
nilpayloads become204 No Content. Non-nilpayloads are serialized before committing200 OKand use JSON shaped like{"data": ...}. -
JSONError()Default error encoder. It understands wrapped
HTTPErrorvalues and pointers, timeouts, cancellations, and request-body-limit failures and renders a JSON error response. Explicit final status codes from200through599are accepted; invalid positive codes fail closed to500.
-
HandleHTTP(...)Registers a raw
http.Handlerroute. Use this when the endpoint needs direct response control for streaming, SSE, proxying, upgrades, hijacking, or existing handler reuse. -
EndpointOptionRoute-level configuration hook used by both
Handle(...)andHandleHTTP(...). The config type itself is internal; callers use the exportedWith...endpoint helpers below rather than constructing endpoint options directly.
-
Run(...)Standard lifecycle path. It listens on the configured address, builds the handler stack, marks readiness on startup unless readiness was set explicitly, and performs graceful shutdown on context cancellation or
SIGINT/SIGTERM. Every exit clears readiness. Failed graceful shutdown is followed by forced closure of ordinary server-owned connections and a joined serve loop. -
RunWithShutdownContext(...)Advanced lifecycle path for a service coordinator that owns a broader shutdown budget. It invokes a
ShutdownContextFactoryafter readiness becomes false and uses the returned outer context to bound the drain delay and graceful HTTP shutdown.WithShutdownTimeout(...)remains an inner HTTP shutdown cap. -
ShutdownContextFactoryCreates the outer context when coordinated shutdown begins. The caller owns cancellation of the returned context and may reuse it for later service shutdown phases.
-
Handler()Builds the final wrapped handler stack without starting a listener. Use this when another component owns the outer
http.Server. -
SetReady(...)Sets the readiness state exposed by
/readyzand opts the server into explicit readiness ownership. -
Ready()Returns the current readiness state.
-
ReadinessCheckLightweight readiness predicate used by the built-in
/readyzendpoint. Returning an error marks the service not ready. Servekit logs the error at debug level and returns a stable generic reason instead of exposing the error text. The predicate should read local or cached state rather than perform active dependency checks.Shape:
func(context.Context) error
-
HTTPErrorError type for handlers that need explicit HTTP status control instead of the default error mapping. Servekit recognizes both values and pointers, including through wrapped error chains.
-
HTTPError.StatusCodeThe final HTTP status Servekit should return for the error. Values from
200through599are used directly. Zero and negative values leave status selection to the default error mapping; other values fail closed to500. -
HTTPError.MessageThe client-facing error text.
-
HTTPError.ErrThe wrapped underlying cause, when present.
-
HTTPError.Error()Implements the
errorinterface. -
HTTPError.Unwrap()Exposes the wrapped cause for
errors.Is(...)anderrors.As(...). -
Error(...)Convenience constructor for
HTTPError.
-
MiddlewareStandard middleware shape used throughout Servekit.
Shape:
func(http.Handler) http.Handler -
Chain(...)Applies middleware in declaration order.
-
RequestID()Ensures the request has an
X-Request-IDheader and stores that value in request context. -
CorrelationID()Ensures the request has an
X-Correlation-IDheader and stores that value in request context. -
AccessLog(...)Emits one structured log entry per completed request.
-
SkipAccessLog()Marks a request so
AccessLog(...)omits it. -
Recovery(...)Panic recovery middleware. In default mode it logs normal panics, writes a best-effort JSON
500before response commitment, and transport-aborts after commitment. In propagation mode it transport-aborts normal panics regardless of commitment. An incominghttp.ErrAbortHandleris always preserved without additional panic logging. -
RequestIDFromContext(...)Returns the request ID stored in request context.
-
CorrelationIDFromContext(...)Returns the correlation ID stored in request context.
-
TraceIDFromContext(...)Returns the active trace ID from request context when tracing is active.
-
SpanIDFromContext(...)Returns the active span ID from request context when tracing is active.
-
WithAddr(addr string)Sets the TCP listen address used by
Run(...). Default::8080. -
WithReadTimeout(timeout time.Duration)Sets
http.Server.ReadTimeout. Default:5s. -
WithReadHeaderTimeout(timeout time.Duration)Sets
http.Server.ReadHeaderTimeout. Default:2s. -
WithWriteTimeout(timeout time.Duration)Sets
http.Server.WriteTimeout. Default:10s. Streaming and proxy routes often need a different value or zero. -
WithIdleTimeout(timeout time.Duration)Sets
http.Server.IdleTimeout. Default:60s. -
WithMaxHeaderBytes(n int)Sets
http.Server.MaxHeaderByteswhenn > 0. Default:1 MiB. -
WithShutdownTimeout(timeout time.Duration)Sets the timeout used for graceful shutdown. If it expires,
Runforce-closes remaining ordinary server-owned connections. Default:15s. -
WithShutdownDrainDelay(delay time.Duration)Waits after readiness flips false and before shutdown begins, giving load balancers time to observe
/readyz.
-
WithLogger(logger *slog.Logger)Sets the logger used by built-in middleware and server internals.
-
WithHTTPServerErrorLog(logger *log.Logger)Advanced override for
http.Server.ErrorLog. -
WithHTTPServerErrorLogLevel(level slog.Level)Sets the slog level used when Servekit derives
http.Server.ErrorLogfrom the server logger's handler.
-
WithMux(mux *http.ServeMux)Replaces the underlying mux. Use this when the service already has an
http.ServeMuxand wants Servekit to register into it. -
WithMiddleware(mw ...Middleware)Appends global middleware to the server-wide handler stack.
-
WithResponseEncoder(encoder ResponseEncoder)Replaces the default success encoder used by
Handle(...). -
WithErrorEncoder(encoder ErrorEncoder)Replaces the default error encoder used by
Handle(...). -
WithBuildInfo(version, commit, date string)Overrides the version metadata served by the built-in
/versionendpoint.
-
WithHealthHandler(handler http.Handler)Mounts a user-defined
GET /healthzendpoint. -
WithReadinessChecks(checks ...ReadinessCheck)Appends lightweight predicates evaluated by the built-in
/readyzendpoint after Servekit lifecycle readiness and, when configured, Opskit readiness. Failure details are debug-logged and replaced by a stable generic reason in the public response. For composed Kit Series services, prefer an Opskit registry as the shared readiness path. -
WithOps(registry *opskit.Registry, opts ...OpsOption)Wires the shared Opskit registry into Servekit's operational presentation.
/readyzincludes Opskit readiness after Servekit lifecycle readiness is true. Admin component routes are not exposed unlessWithOpsAdmin()is supplied. Servekit does not depend on the domain kits that registered components. -
OpsOptionConfiguration hook for Servekit's Opskit presentation.
-
WithOpsAdmin()Enables read-only Opskit admin routes:
GET /admin/componentsandGET /admin/components/{name}. -
WithOpsAdminAuthGate(fn func(*http.Request) error)Configures an endpoint-style auth gate for Opskit admin routes when they are enabled with
WithOpsAdmin(). The gate may return anHTTPErrorvalue or pointer to control the denial response. A nil gate is ignored. -
WithOpsTimeout(timeout time.Duration)Supplies a context deadline for Opskit readiness and component snapshot reads. Default:
2s. Use zero or a negative duration to rely only on the incoming request context. Component implementations must observe context cancellation. -
WithDefaultEndpointsEnabled(enabled bool)Enables or disables the built-in probe/version endpoints:
GET /livez,GET /readyz,GET /version, andGET /healthzwhen configured. This does not disable opt-in Opskit admin routes enabled withWithOpsAdmin().
-
WithRequestBodyLimit(n int64)Sets the default request-body limit for all endpoints. Default:
4 MiB. Use-1to disable the limit globally.
-
WithRecoveryEnabled(enabled bool)Enables or disables Servekit's outer panic recovery middleware.
-
WithPanicPropagation(enabled bool)Makes normal panics use abort-style propagation with
http.ErrAbortHandlereven before response commitment. Default recovery already aborts committed responses. -
WithAccessLogEnabled(enabled bool)Enables or disables access-log middleware.
-
WithRequestIDEnabled(enabled bool)Enables or disables request ID middleware.
-
WithCorrelationIDEnabled(enabled bool)Enables or disables correlation ID middleware.
-
WithOpenTelemetryEnabled(enabled bool)Enables or disables built-in OpenTelemetry tracing and metrics middleware. On the normal
Run(...)path, that also controls Servekit's server connection metrics.
Servekit's default path already includes request-level tracing and metrics. On the Run(...) path it also records server connection metrics. These options exist for teams that want to replace or shape that telemetry policy.
-
WithTracerProvider(tp trace.TracerProvider)Sets the tracer provider used by Servekit's tracing middleware. When unset, Servekit uses
otel.GetTracerProvider(). -
WithMeterProvider(mp metric.MeterProvider)Sets the meter provider used by Servekit's metrics middleware. When unset, Servekit uses
otel.GetMeterProvider(). -
WithPropagator(p propagation.TextMapPropagator)Sets the text-map propagator used to extract incoming trace context. When unset, Servekit uses
otel.GetTextMapPropagator(). -
WithOTelSpanAttributes(fn func(*http.Request) []attribute.KeyValue)Appends request-derived attributes to server spans. Span-only identifiers and other investigative values belong here.
-
WithOTelMetricAttributes(fn func(*http.Request) []attribute.KeyValue)Appends request-derived attributes to built-in request metrics. Values must come from a bounded, low-cardinality set; do not use request IDs, tenant IDs, or raw URLs.
-
WithSpanNameFormatter(fn func(*http.Request, string) string)Overrides span naming. Keep names bounded; prefer route templates over raw paths or arbitrary request methods.
-
WithRouteLabeler(fn func(*http.Request) string)Overrides the low-cardinality route label used for spans and metrics. It must return a bounded route template, not a concrete request path.
-
WithOTelPanicMetricEnabled(enabled bool)Enables or disables panic counter metrics.
-
WithCORSConfig(cfg CORSConfig)Opts into Servekit's built-in CORS middleware. CORS is disabled by default.
-
WithEndpointMiddleware(mw ...Middleware)Appends middleware for one route only. Endpoint timeout, body-limit, and auth policy run before this middleware.
-
WithEndpointTimeout(timeout time.Duration)Applies a request-context timeout to one route.
-
WithBodyLimit(n int64)Overrides the server-wide request-body limit for one route. Use
-1to disable the limit for that route. -
WithAuthCheck(check func(*http.Request) bool)Adds a simple allow-or-deny auth gate. When it returns false, Servekit responds with HTTP
401. -
WithAuthGate(fn func(*http.Request) error)Adds an error-returning auth gate for richer or more specific auth failure behavior. The gate may return an
HTTPErrorvalue or pointer to control the response status and message. -
WithEndpointResponseEncoder(encoder ResponseEncoder)Overrides success encoding for one
Handle(...)route without changing the rest of the server. -
WithSkipAccessLog()Suppresses access-log output for one route.
-
WithSkipTelemetry()Suppresses built-in tracing and metrics for one route.
-
CORSConfigConfigures Servekit's opt-in browser CORS middleware.
-
CORSConfig.AllowedOrigins []stringExact origin allowlist in
scheme://host[:port]form. When empty and credentials are disabled, Servekit allows all origins. -
CORSConfig.AllowedMethods []stringAllowlist returned on successful preflight responses. When empty, Servekit uses a conservative default set of common HTTP methods.
-
CORSConfig.AllowedHeaders []stringAllowlist for
Access-Control-Request-Headerson preflight requests. When empty, Servekit uses a small default set. -
CORSConfig.ExposedHeaders []stringResponse headers browsers may expose to calling JavaScript on successful cross-origin requests.
-
CORSConfig.AllowCredentials boolEnables
Access-Control-Allow-Credentials: true. When true,AllowedOriginsmust be explicit and must not contain"*". -
CORSConfig.MaxAge intControls
Access-Control-Max-Ageon successful preflight responses.0uses Servekit's default of600seconds. Negative disables the header.
The version subpackage keeps build metadata reusable outside the server itself.
-
VersionThe application or module version. Usually set with
-ldflags, but Servekit also attempts to populate it from Go build info for local builds. -
CommitThe short VCS revision, when available.
-
DateThe build or VCS timestamp, when available.
-
InfoSerialized build metadata payload used by the built-in
/versionendpoint and reusable elsewhere in the application. -
Info.Version stringApplication or module version.
-
Info.Commit stringShort VCS revision.
-
Info.Date stringBuild or VCS timestamp.
-
Info.GoVersion stringGo runtime version for the running binary.
-
Get()Snapshots the current build metadata variables into an
Infovalue. -
Info.String()Formats
Infoas a compact single-line summary. -
Info.Handler()Returns an
http.Handlerthat serves theInfovalue as JSON.
If you are new to the codebase: