Introduces code.nochebuena.dev/einherjar/web — the HTTP transport layer of the
Einherjar framework. Absorbs httpserver, httpmw, and httputil from micro-lib,
replacing gorilla/mux with chi, adopting SecurityBag-native middleware, and
centralizing error handling through a single httputil.Error function.
server:
- Server interface — embeds lifecycle.Component and chi.Router
- Config struct (EINHERJAR_SERVER_* env vars); DefaultConfig
- New(logger, cfg, opts...) Server; WithMiddleware option
- Binds TCP synchronously in OnStart; logs "server: listening" on success
- Graceful shutdown within ShutdownTimeout on OnStop
mw:
- Recover — catches panics, returns 500, logs at Error
- RequestID — injects UUID v7 (UUID v4 fallback) into context and X-Request-ID header
- RequestLogger — structured access log per request
- CORS / CORSAllowAll — chi-based, applied only when origins non-empty
- IPRateLimit / UserRateLimit — pluggable RateLimiterStore interface
- InMemoryRateLimiterStore — token-bucket backed by golang.org/x/time/rate;
background goroutine evicts stale entries every 5 minutes
- StatusRecorder — wraps ResponseWriter to capture HTTP status code
httputil:
- Handle[Req, Res] / HandleNoBody[Res] / HandleEmpty[Req] — generic handler adapters
- Error(logger, w, r, err) — derives log level from status (≥500→Error, 4xx→Warn,
499→Info); writes standardized JSON body; logz enriches *xerrors.Err automatically
- JSON(w, status, v) / NoContent(w) — response helpers
- HandlerFunc adapter type
health:
- NewHandler / NewHandlerWithConfig — runs all Checkable checks concurrently;
returns JSON {status, components} with per-component latency and error
- Config struct (EINHERJAR_HEALTH_CHECK_TIMEOUT, default 5s)
Root factory:
- web.New(logger, cfg...) Server — composes Recover+RequestID+RequestLogger+CORS
in outermost-first order; CORS applied only when AllowedOrigins non-empty
- server.Server interface and web/server/identifiable.go: embeds observability.Identifiable;
ModulePath and ModuleVersion read via runtime/debug.ReadBuildInfo() — prints in launcher banner
45 lines
1.7 KiB
Go
45 lines
1.7 KiB
Go
// Package httputil provides typed handler adapters and HTTP response helpers.
|
|
//
|
|
// Handler adapters eliminate HTTP boilerplate — business functions stay pure Go
|
|
// with no knowledge of request parsing or response encoding. All errors flow
|
|
// through a centralized [Error] handler that logs once at the correct level and
|
|
// writes a standardized JSON response body.
|
|
//
|
|
// # Typed handler adapters
|
|
//
|
|
// type CreateUserReq struct {
|
|
// Email string `json:"email" validate:"required,email"`
|
|
// }
|
|
// type CreateUserRes struct {
|
|
// ID string `json:"id"`
|
|
// }
|
|
//
|
|
// r.Post("/users", httputil.Handle(v, logger, func(ctx context.Context, req CreateUserReq) (CreateUserRes, error) {
|
|
// u, err := svc.CreateUser(ctx, req.Email)
|
|
// if err != nil {
|
|
// return CreateUserRes{}, err // propagates to Error — logged once, correct HTTP status
|
|
// }
|
|
// return CreateUserRes{ID: u.ID}, nil
|
|
// }))
|
|
//
|
|
// # Centralized error handler
|
|
//
|
|
// [Error] is the single point of error processing for all handlers:
|
|
// - 5xx → Error level (logz auto-enriches with error_code and WithContext fields)
|
|
// - 4xx → Warn level (client mistake — not a server failure)
|
|
// - 499 → Info level (client cancelled the request intentionally)
|
|
//
|
|
// Call it directly from [HandlerFunc] when you need path parameters or custom logic:
|
|
//
|
|
// r.Get("/users/{id}", httputil.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
|
// id := chi.URLParam(r, "id")
|
|
// u, err := svc.GetUser(r.Context(), id)
|
|
// if err != nil {
|
|
// httputil.Error(logger, w, r, err)
|
|
// return nil
|
|
// }
|
|
// httputil.JSON(w, http.StatusOK, u)
|
|
// return nil
|
|
// }).ServeHTTP)
|
|
package httputil
|