Server
server is the kit's HTTP chassis: a chi router over the standard net/http, with the kit's error handling, validation and telemetry wired in, run under the shared lifecycle. Its positioning is stdlib-first: chi is not a framework, it is routing over net/http. Every middleware is a plain func(http.Handler) http.Handler, every handler is http.HandlerFunc-compatible, so any net/http tool in the Go ecosystem (middleware libraries, httptest, profilers) works unmodified.
import "github.com/gp-system/gpsystem/server"
It is the chassis every generated project sits on; application code never talks to net/http directly, it calls server.Run once, in main.
Config
In a generated project, server.Config is embedded without a prefix in the application config and loaded from environment variables by envconf.MustLoad:
type Config struct {
Server server.Config
DB dbx.Config `envPrefix:"DB_"`
// ...
}
The fields and their environment variables:
| Field | Env | Default | What it controls |
|---|---|---|---|
ListenAddr | LISTEN_ADDR | :3000 | the address the server listens on |
ShutdownTimeout | SHUTDOWN_TIMEOUT | 10s | how long in-flight requests get after SIGINT/SIGTERM |
ReadHeaderTimeout | READ_HEADER_TIMEOUT | 5s | how long a client may take to send request headers (Slowloris defense) |
ReadTimeout | READ_TIMEOUT | 30s | budget for reading the whole request (headers + body) |
WriteTimeout | WRITE_TIMEOUT | 0s (disabled) | budget for writing the response |
IdleTimeout | IDLE_TIMEOUT | 120s | how long an idle keep-alive connection stays open |
CORSOrigins | CORS_ORIGINS | * | allowed origins, comma-separated |
BodyLimit | BODY_LIMIT | 4194304 (4 MiB) | max request body size in bytes |
ExposeInternalErrors | HTTP_EXPOSE_INTERNAL_ERRORS | false | internal error details in 5xx responses (dev only!) |
Telemetry | (embedded) | none | telemetry.Config (OTel, logger, Sentry) |
The full env reference (including the DB, worker and telemetry variables): Configuration reference.
Timeouts
The defaults are tuned for production traffic, not demos:
ReadHeaderTimeoutis the first line of Slowloris defense: a client that drips headers byte by byte gets disconnected after 5 seconds.ReadTimeoutcovers reading the whole request.WriteTimeoutis deliberately0(disabled): it would also cut off slow or streaming responses (large downloads, SSE). Enable it when all your endpoints are short-lived.
Body limit: never accidentally disabled
const DefaultBodyLimit = 4 << 20 // 4 MiB
func (c Config) EffectiveBodyLimit() int
server never reads the raw BodyLimit field; it calls EffectiveBodyLimit(): a 0 or negative value does not mean "unlimited", it falls back to the 4 MiB default. A typo'd or empty BODY_LIMIT therefore cannot silently remove the cap. Exceeding the limit produces a 413 problem response.
HTTP_EXPOSE_INTERNAL_ERRORS
With true, 5xx responses carry the underlying error message in detail, and, when the chain holds an errs error, the response also gains stack and chain extension members. It is deliberately a separate switch from OTEL_DEV_MODE: turning on dev logging can never accidentally start leaking internals to clients. Keep it false in production: details go to the log and Sentry there, not into the response.
The embedded telemetry config
The Telemetry field is a telemetry.Config: settings for the OTel bootstrap, the default slog logger and the optional Sentry integration (OTEL_SERVICE_NAME, OTEL_DEV_MODE, LOG_LEVEL, SENTRY_DSN, ..., all standard names, no prefix). server.Run calls telemetry.Setup from it before anything else starts. Details: Observability.
The shared lifecycle
server does not implement graceful shutdown itself: it delegates to the engine-agnostic app package, the same one worker and realtime sit on. The flow is identical in every gpsystem process:
telemetry.Setup: OTel, logger, Sentry.- Route registration (your
registerfunction). - Listen: the process blocks from here.
- On
SIGINT/SIGTERM: the server stops accepting requests and drains in-flight ones withinShutdownTimeout. A second signal kills the process immediately. - Cleanups registered with
WithCloserrun in LIFO order (with their own grace period, even when the drain consumed the budget). - Telemetry flushes last: spans emitted by closers still get exported.
The exact ordering and signal-handling details live on the Application lifecycle page; this page covers what server.Run itself wires on top of that shared skeleton.
server.Config carries the full web-server configuration: every field is loaded from an environment variable, typed, and graceful shutdown is the binary's job, not an external process manager's.What server.Run wires
func Run(ctx context.Context, cfg Config, register RegisterFunc, opts ...Option) error
func New(cfg Config, opts ...Option) *chi.Mux // for tests and special cases
type RegisterFunc func(r chi.Router) error
Run blocks until exit: telemetry bootstrap → router construction → register(r) → http.Server + ListenAndServe → graceful shutdown on SIGINT/SIGTERM. It returns nil on clean shutdown. New returns the fully wired router without running it or bootstrapping telemetry: you pair it with httptest (see Testing).
The middleware chain and the router-level handlers, in this order:
| What | From | What it does |
|---|---|---|
| recoverer | kit | a panic becomes an errs error whose stack points at the panic site, rendered as a 500 problem response (it re-raises http.ErrAbortHandler, net/http's flow-control signal) |
| validator injector | kit | puts the validator given via WithValidator into the request context, where StrictValidator(nil) finds it (see below) |
| OTel middleware | otelhttp | per-request server span + HTTP metrics: OpenTelemetry |
| Sentry request hub | kit | an isolated Sentry hub per request, so breadcrumbs never mix across requests; no-op when Sentry is off |
| dev logger | chi/middleware.Logger | only with OTEL_DEV_MODE=true: request log on the console |
| CORS | go-chi/cors | from CORS_ORIGINS; GET/POST/PUT/PATCH/DELETE/OPTIONS, Content-Type + Authorization headers |
| body limit | chi/middleware.RequestSize | wraps the body in http.MaxBytesReader with cfg.EffectiveBodyLimit(): exceeding it yields a 413 problem |
NotFound / MethodNotAllowed | kit | 404/405 as problem+json instead of chi's stock plain-text errors; mounted subrouters inherit them |
The server.Config timeouts translate into the http.Server (ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout).
Error rendering: net/http has no central error handler
Unlike frameworks with a built-in error hook, net/http gives a handler no way to "return" an error to the framework: a handler writes the response itself. The kit bridges this at three points so the on-the-wire behavior is uniform everywhere:
- the generated server code's error hooks are wired to the
httperrnet/http writers (WriteError,WriteBadRequest): an error returned from your handler goes through the full mapping; - the router-level cases (panic, 404, 405, body limit) are rendered as problems per the table above;
- request validation does not run at bind time (the strict server decodes with
json.Decoder) but in theserver.StrictValidatorstrict middleware (see below).
The shop entry point
The sample app's HTTP binary, every line of which was written by the generator:
package main
import (
"context"
"log"
"github.com/go-chi/chi/v5"
"github.com/gp-system/dbx/pg"
"github.com/gp-system/envconf"
"github.com/gp-system/events/outbox"
"github.com/gp-system/gpsystem/server"
"github.com/acme/shop/internal/modules/shop"
"github.com/acme/shop/internal/platform/config"
)
func main() {
cfg := envconf.MustLoad[config.Config]()
ctx := context.Background()
pool := pg.MustNewPool(ctx, cfg.DB)
err := server.Run(ctx, cfg.Server, func(r chi.Router) error {
api := chi.NewRouter()
deps := shop.Dependencies{
DB: pg.NewDB(pool),
Transactor: pg.NewTransactor(pool),
Dispatcher: outbox.NewDispatcher(outbox.NewStore(pg.NewDB(pool))),
}
shop.RegisterApi(api, deps)
shop.RegisterAdmin(api, deps)
r.Mount("/api/v1", api)
return nil
}, server.WithCloser("pgxpool", func(context.Context) error {
pool.Close()
return nil
}))
if err != nil {
log.Fatal(err)
}
}
Prefixing happens with Mount: each module's surfaces register on a fresh subrouter, which gets mounted under /api/v1.
Options
server.WithCloser("pgxpool", func(ctx context.Context) error { pool.Close(); return nil })
server.WithMiddleware(myRateLimiter, myRequestID) // ...func(http.Handler) http.Handler
server.WithHTTPServer(func(s *http.Server) { s.MaxHeaderBytes = 1 << 16 })
server.WithValidator(validate.New(validate.WithRegister(registerCustomTags)))
server.WithoutTelemetry() // tests / external OTel setup
WithCloser(name, fn): cleanup during graceful shutdown, after the server has stopped accepting requests. Closers run in LIFO order; telemetry flushes last, so a span emitted in a closer still gets exported.WithMiddleware(...func(http.Handler) http.Handler): router-level middleware after the kit defaults. The standard net/http middleware shape: any ecosystem middleware fits here. Anything needed by a single surface only should go on that surface'sRouteinstead (see below).WithHTTPServer(func(*http.Server)): escape hatch forhttp.Serverfields the kit does not expose (TLS,MaxHeaderBytes, ...). You may also override the kit-set fields: your mutation runs last.WithValidator(*validate.Validator): the application-wide request validator, typically one carrying custom validation tags;StrictValidator(nil)middlewares resolve it at request time.WithoutTelemetry(): skipstelemetry.Setupand the OTel middleware; for tests, or when the process configures telemetry itself.
RegisterFunc and StrictValidator
add surface splices one Register<Surface> function per surface into the module's register.go. For the shop's api surface this is generated verbatim:
func RegisterApi(router chi.Router, deps Dependencies) {
apiSvc := apiservice.New()
apiHandler := apihttp.New(apiSvc)
apiPolicies := apipolicy.New()
router.Route("/shop", func(r chi.Router) {
shopapigen.HandlerWithOptions(shopapigen.NewStrictHandlerWithOptions(
apiHandler,
[]shopapigen.StrictMiddlewareFunc{
server.StrictValidator[shopapigen.StrictHandlerFunc](nil),
// Last = outermost: authorization runs before validation.
kitpolicy.Enforcer[shopapigen.StrictHandlerFunc](apiPolicies, shopapigen.PermissionByOperation, shopapigen.PolicyByOperation),
},
shopapigen.StrictHTTPServerOptions{
RequestErrorHandlerFunc: httperr.WriteBadRequest,
ResponseErrorHandlerFunc: server.WriteError,
},
), shopapigen.ChiServerOptions{
BaseRouter: r,
ErrorHandlerFunc: httperr.WriteBadRequest,
})
})
}
Line by line:
- Service → handler → policy registry: an explicit construction, no container involved.
router.Route("/shop", ...): theapisurface sits at the module root (/api/v1/shop/...); every other surface under its own prefix (/admin/shop).NewStrictHandlerWithOptions: the generated strict server, plus the error hooks: request-decoding failures (RequestErrorHandlerFunc,ErrorHandlerFunc) render as 400 viahttperr.WriteBadRequest, your handler's errors (ResponseErrorHandlerFunc) viaserver.WriteError, which maps theauth/rbac/policysentinels onto Problems and delegates everything else tohttperr.WriteError, through the full mapping.server.StrictValidator+kitpolicy.Enforcer: validation and policy enforcement as strict middleware; the last element of the slice wraps outermost, so the enforcer runs before the validator.
StrictValidator: validation before the handler
func StrictValidator[H ~func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error)](
v *validate.Validator,
) func(f H, operationID string) H
The strict server decodes with json.Decoder, without validation. StrictValidator closes that gap: it validates the fully bound request object (parameters + body) with the kit validator before your handler runs; a failure surfaces as a 422 problem through ResponseErrorHandlerFunc. The type parameter exists because oapi-codegen defines StrictHandlerFunc per generated package.
The validator is resolved per request, in this order: the explicit v argument → the one set via server.WithValidator (from the context) → validate.New(). That's why the generated code passes nil: a single WithValidator option in main.go applies application-wide, and the generated files need no edits.
Surface middleware
Router-level middleware comes from WithMiddleware; anything scoped to one surface (like the JWT protection of the shop's admin surface) you wire inside the surface's Route block with the kit's net/http auth middleware pair, server.AuthMiddleware and server.RequireRole:
import (
"github.com/gp-system/auth"
// ...
)
type Dependencies struct {
DB *pg.DB
Transactor dbx.Transactor
Auth auth.Config // JWT_SECRET, JWT_ISSUER, ..., from the platform config
// gpsystem:dependencies
}
func RegisterAdmin(router chi.Router, deps Dependencies) {
adminSvc := adminservice.New()
adminHandler := adminhttp.New(adminSvc)
adminPolicies := adminpolicy.New()
router.Route("/admin/shop", func(r chi.Router) {
r.Use(server.AuthMiddleware(deps.Auth), server.RequireRole("admin"))
shopadmingen.HandlerWithOptions(shopadmingen.NewStrictHandlerWithOptions(
adminHandler,
[]shopadmingen.StrictMiddlewareFunc{
server.StrictValidator[shopadmingen.StrictHandlerFunc](nil),
kitpolicy.Enforcer[shopadmingen.StrictHandlerFunc](adminPolicies, shopadmingen.PermissionByOperation, shopadmingen.PolicyByOperation),
},
shopadmingen.StrictHTTPServerOptions{
RequestErrorHandlerFunc: httperr.WriteBadRequest,
ResponseErrorHandlerFunc: server.WriteError,
},
), shopadmingen.ChiServerOptions{
BaseRouter: r,
ErrorHandlerFunc: httperr.WriteBadRequest,
})
})
}
server.AuthMiddleware parses the Bearer token and puts an rbac.Identity into the context; server.RequireRole("admin") short-circuits with a 403 problem without that role. Every /api/v1/admin/shop/... route is protected. The api surface's public routes are untouched.
server.WithMiddleware; surface-level (auth, role) → r.Use in the surface's Route block; operation-level (permission, ownership check) → @permission/@policy in the spec, enforced by the enforcer.Testing
New returns the fully wired router; you test with plain net/http/httptest:
r := server.New(server.Config{}, server.WithoutTelemetry())
r.Post("/things", createThing)
srv := httptest.NewServer(r)
defer srv.Close()
resp, err := http.Post(srv.URL+"/things", "application/json", body)
The panic recoverer, the 404/405 problem handlers and the body limit are active here too, so the test sees exactly the problem+json response the client will.
Patterns used
- Context-injected validator (
injectValidator/validatorFromContext, with an unexported context key): Design patterns. - Generic middleware adapter (
StrictValidator[H ~func(...)], fitting every generatedStrictHandlerFunc): Design patterns.
Related pages
- Application lifecycle: the shared
app.Runskeletonserver.Runbuilds on. - Error responses: the full error-mapping table.
- Validation: custom validation tags.
- Policies: the enforcer used above.