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:
16
server/config.go
Normal file
16
server/config.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package server
|
||||
|
||||
import "time"
|
||||
|
||||
// Config holds HTTP server configuration.
|
||||
// All fields carry caarlos0/env struct tags — applications supply the loader.
|
||||
type Config struct {
|
||||
Host string `env:"EINHERJAR_SERVER_HOST" envDefault:"0.0.0.0"`
|
||||
Port int `env:"EINHERJAR_SERVER_PORT" envDefault:"8080"`
|
||||
ReadTimeout time.Duration `env:"EINHERJAR_SERVER_READ_TIMEOUT" envDefault:"5s"`
|
||||
WriteTimeout time.Duration `env:"EINHERJAR_SERVER_WRITE_TIMEOUT" envDefault:"10s"`
|
||||
IdleTimeout time.Duration `env:"EINHERJAR_SERVER_IDLE_TIMEOUT" envDefault:"120s"`
|
||||
ShutdownTimeout time.Duration `env:"EINHERJAR_SERVER_SHUTDOWN_TIMEOUT" envDefault:"10s"`
|
||||
}
|
||||
|
||||
const defaultShutdownTimeout = 10 * time.Second
|
||||
51
server/doc.go
Normal file
51
server/doc.go
Normal file
@@ -0,0 +1,51 @@
|
||||
// Package server provides a lifecycle-aware HTTP server for Einherjar services.
|
||||
//
|
||||
// [Server] embeds both [lifecycle.Component] and [chi.Router], so it plugs
|
||||
// directly into [launcher.New] and exposes the full chi routing API.
|
||||
//
|
||||
// For the happy path use [web.New], which pre-wires the recommended middleware
|
||||
// stack. Use this package directly when you need explicit control over
|
||||
// middleware order, a custom request-ID generator, or any other deviation from
|
||||
// the defaults.
|
||||
//
|
||||
// # Basic usage
|
||||
//
|
||||
// srv := server.New(logger, server.Config{Port: 8080},
|
||||
// server.WithMiddleware(
|
||||
// mw.Recover(),
|
||||
// mw.RequestID(myIDGenerator),
|
||||
// mw.RequestLogger(logger),
|
||||
// mw.CORS([]string{"https://example.com"}),
|
||||
// ),
|
||||
// )
|
||||
//
|
||||
// srv.Get("/health", health.NewHandler(logger, db))
|
||||
//
|
||||
// lc := launcher.New(logger)
|
||||
// lc.Append(srv)
|
||||
// lc.BeforeStart(func() error {
|
||||
// srv.Mount("/v1", apiRouter)
|
||||
// return nil
|
||||
// })
|
||||
// if err := lc.Run(); err != nil {
|
||||
// logger.Error("launcher failed", err)
|
||||
// os.Exit(1)
|
||||
// }
|
||||
//
|
||||
// # Lifecycle
|
||||
//
|
||||
// [Server.OnInit] applies registered middleware to the router.
|
||||
// [Server.OnStart] binds the TCP listener synchronously — a port conflict
|
||||
// surfaces immediately rather than silently dropping the server. Requests
|
||||
// are served in a background goroutine.
|
||||
// [Server.OnStop] performs a graceful shutdown within [Config.ShutdownTimeout].
|
||||
//
|
||||
// # Environment variables
|
||||
//
|
||||
// EINHERJAR_SERVER_HOST=0.0.0.0 bind address (default 0.0.0.0)
|
||||
// EINHERJAR_SERVER_PORT=8080 listen port (default 8080)
|
||||
// EINHERJAR_SERVER_READ_TIMEOUT=5s HTTP read timeout (default 5s)
|
||||
// EINHERJAR_SERVER_WRITE_TIMEOUT=10s HTTP write timeout (default 10s)
|
||||
// EINHERJAR_SERVER_IDLE_TIMEOUT=120s keep-alive idle timeout (default 120s)
|
||||
// EINHERJAR_SERVER_SHUTDOWN_TIMEOUT=10s graceful shutdown budget (default 10s)
|
||||
package server
|
||||
21
server/identifiable.go
Normal file
21
server/identifiable.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package server
|
||||
|
||||
import "runtime/debug"
|
||||
|
||||
const modulePath = "code.nochebuena.dev/einherjar/web"
|
||||
|
||||
func (s *impl) ModulePath() string { return modulePath }
|
||||
|
||||
func (s *impl) ModuleVersion() string {
|
||||
if info, ok := debug.ReadBuildInfo(); ok {
|
||||
for _, dep := range info.Deps {
|
||||
if dep.Path == modulePath {
|
||||
return dep.Version
|
||||
}
|
||||
}
|
||||
if info.Main.Path == modulePath {
|
||||
return info.Main.Version
|
||||
}
|
||||
}
|
||||
return "(devel)"
|
||||
}
|
||||
19
server/option.go
Normal file
19
server/option.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package server
|
||||
|
||||
import "net/http"
|
||||
|
||||
// Option configures a [Server] at construction time.
|
||||
type Option func(*serverOpts)
|
||||
|
||||
// WithMiddleware registers one or more middleware functions applied to the
|
||||
// root chi router during [lifecycle.Component.OnInit].
|
||||
// Middleware is applied in registration order (outermost first).
|
||||
func WithMiddleware(middleware ...func(http.Handler) http.Handler) Option {
|
||||
return func(o *serverOpts) {
|
||||
o.middleware = append(o.middleware, middleware...)
|
||||
}
|
||||
}
|
||||
|
||||
type serverOpts struct {
|
||||
middleware []func(http.Handler) http.Handler
|
||||
}
|
||||
37
server/server.go
Normal file
37
server/server.go
Normal file
@@ -0,0 +1,37 @@
|
||||
// Package server provides a lifecycle-managed chi HTTP server.
|
||||
//
|
||||
// The server implements [lifecycle.Component] from contracts, making it
|
||||
// directly compatible with [launcher.New] without any adapter layer.
|
||||
//
|
||||
// # Example
|
||||
//
|
||||
// srv := server.New(logger, server.Config{Port: 8080},
|
||||
// server.WithMiddleware(
|
||||
// mw.Recover(),
|
||||
// mw.RequestID(uuid.NewString),
|
||||
// mw.RequestLogger(logger),
|
||||
// ),
|
||||
// )
|
||||
//
|
||||
// lc := launcher.New(logger)
|
||||
// lc.Append(srv)
|
||||
// lc.BeforeStart(func() error {
|
||||
// srv.Get("/health", healthHandler)
|
||||
// return nil
|
||||
// })
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/lifecycle"
|
||||
"code.nochebuena.dev/einherjar/contracts/observability"
|
||||
)
|
||||
|
||||
// Server is a lifecycle-managed HTTP server that exposes a chi router.
|
||||
// Embed chi.Router gives callers the full routing API: Get, Post, Route, Mount, Use, etc.
|
||||
type Server interface {
|
||||
lifecycle.Component
|
||||
observability.Identifiable
|
||||
chi.Router
|
||||
}
|
||||
103
server/server_impl.go
Normal file
103
server/server_impl.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||
"code.nochebuena.dev/einherjar/contracts/observability"
|
||||
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||
)
|
||||
|
||||
var _ Server = (*impl)(nil)
|
||||
var _ observability.Identifiable = (*impl)(nil)
|
||||
|
||||
type impl struct {
|
||||
chi.Router
|
||||
logger logging.Logger
|
||||
cfg Config
|
||||
opts serverOpts
|
||||
srv *http.Server
|
||||
}
|
||||
|
||||
// New creates a [Server]. No middleware is applied by default; use [WithMiddleware]
|
||||
// to compose the middleware stack before passing it to [launcher.New].
|
||||
func New(logger logging.Logger, cfg Config, opts ...Option) Server {
|
||||
o := serverOpts{}
|
||||
for _, opt := range opts {
|
||||
opt(&o)
|
||||
}
|
||||
return &impl{
|
||||
Router: chi.NewRouter(),
|
||||
logger: logger,
|
||||
cfg: cfg,
|
||||
opts: o,
|
||||
}
|
||||
}
|
||||
|
||||
// OnInit applies registered middleware to the router.
|
||||
func (s *impl) OnInit() error {
|
||||
for _, mw := range s.opts.middleware {
|
||||
s.Router.Use(mw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnStart binds the TCP listener synchronously so that a port conflict surfaces
|
||||
// immediately — the launcher can trigger a clean shutdown instead of running
|
||||
// silently without an HTTP server. Requests are served in a background goroutine.
|
||||
func (s *impl) OnStart() error {
|
||||
host := s.cfg.Host
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
port := s.cfg.Port
|
||||
if port == 0 {
|
||||
port = 8080
|
||||
}
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return xerrors.Unavailable("server: bind %s", addr).WithError(err)
|
||||
}
|
||||
|
||||
s.srv = &http.Server{
|
||||
Addr: addr,
|
||||
Handler: s.Router,
|
||||
ReadTimeout: s.cfg.ReadTimeout,
|
||||
WriteTimeout: s.cfg.WriteTimeout,
|
||||
IdleTimeout: s.cfg.IdleTimeout,
|
||||
}
|
||||
go func() {
|
||||
if err := s.srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
s.logger.Error("server: fatal", err)
|
||||
}
|
||||
}()
|
||||
s.logger.Info("server: listening", "addr", addr)
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnStop performs a graceful shutdown, waiting up to ShutdownTimeout for
|
||||
// in-flight requests to complete. No-op if OnStart was never called.
|
||||
func (s *impl) OnStop() error {
|
||||
if s.srv == nil {
|
||||
return nil
|
||||
}
|
||||
s.logger.Info("server: shutting down")
|
||||
timeout := s.cfg.ShutdownTimeout
|
||||
if timeout == 0 {
|
||||
timeout = defaultShutdownTimeout
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
if err := s.srv.Shutdown(ctx); err != nil {
|
||||
return xerrors.Internal("server: shutdown").WithError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user