feat(web): initial implementation — server, mw, httputil, health (v1.0.0)
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
This commit is contained in:
52
web.go
Normal file
52
web.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||
"code.nochebuena.dev/einherjar/web/mw"
|
||||
"code.nochebuena.dev/einherjar/web/server"
|
||||
)
|
||||
|
||||
// Config aggregates configuration for the web module.
|
||||
// Server holds HTTP server settings; all fields carry caarlos0/env struct tags.
|
||||
// AllowedOrigins is programmatic-only — set it directly or via the env tag.
|
||||
type Config struct {
|
||||
Server server.Config
|
||||
AllowedOrigins []string `env:"EINHERJAR_SERVER_CORS_ORIGINS" envSeparator:","`
|
||||
}
|
||||
|
||||
// New creates a [server.Server] with the recommended middleware stack pre-applied:
|
||||
// 1. Recover — catches panics, returns 500
|
||||
// 2. RequestID — injects UUID v7 request ID (falls back to v4)
|
||||
// 3. RequestLogger — logs method, path, status, latency
|
||||
// 4. CORS — applied only when cfg.AllowedOrigins is non-empty
|
||||
//
|
||||
// For full control over middleware composition use [server.New] directly.
|
||||
func New(logger logging.Logger, cfg ...Config) server.Server {
|
||||
var c Config
|
||||
if len(cfg) > 0 {
|
||||
c = cfg[0]
|
||||
}
|
||||
|
||||
middleware := []func(http.Handler) http.Handler{
|
||||
mw.Recover(logger),
|
||||
mw.RequestID(newRequestID),
|
||||
mw.RequestLogger(logger),
|
||||
}
|
||||
if len(c.AllowedOrigins) > 0 {
|
||||
middleware = append(middleware, mw.CORS(c.AllowedOrigins))
|
||||
}
|
||||
|
||||
return server.New(logger, c.Server, server.WithMiddleware(middleware...))
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return uuid.NewString()
|
||||
}
|
||||
return id.String()
|
||||
}
|
||||
Reference in New Issue
Block a user