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:
44
httputil/doc.go
Normal file
44
httputil/doc.go
Normal file
@@ -0,0 +1,44 @@
|
||||
// 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
|
||||
73
httputil/handle.go
Normal file
73
httputil/handle.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package httputil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||
"code.nochebuena.dev/einherjar/core/valid"
|
||||
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||
)
|
||||
|
||||
// Handle adapts a typed business function to http.HandlerFunc.
|
||||
// - Decodes the JSON request body into Req.
|
||||
// - Validates Req using the provided [valid.Validator].
|
||||
// - Calls fn with the request context and decoded Req.
|
||||
// - Encodes Res as JSON with HTTP 200 on success.
|
||||
// - On error: logs via [Error] (level derived from HTTP status) and writes the standardized JSON body.
|
||||
func Handle[Req, Res any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) (Res, error)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req Req
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
Error(logger, w, r, xerrors.New(xerrors.ErrInvalidInput, "invalid JSON: "+err.Error()))
|
||||
return
|
||||
}
|
||||
if err := v.Struct(req); err != nil {
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
res, err := fn(r.Context(), req)
|
||||
if err != nil {
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
JSON(w, http.StatusOK, res)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleNoBody adapts a typed function with no request body (GET, HEAD).
|
||||
// Calls fn with the request context; encodes the result as JSON with HTTP 200.
|
||||
// On error: logs via [Error] and writes the standardized JSON body.
|
||||
func HandleNoBody[Res any](logger logging.Logger, fn func(ctx context.Context) (Res, error)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
res, err := fn(r.Context())
|
||||
if err != nil {
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
JSON(w, http.StatusOK, res)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleEmpty adapts a typed function with a request body but no response body.
|
||||
// Decodes and validates Req, calls fn, returns 204 No Content on success.
|
||||
// On error: logs via [Error] and writes the standardized JSON body.
|
||||
func HandleEmpty[Req any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) error) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req Req
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
Error(logger, w, r, xerrors.New(xerrors.ErrInvalidInput, "invalid JSON: "+err.Error()))
|
||||
return
|
||||
}
|
||||
if err := v.Struct(req); err != nil {
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := fn(r.Context(), req); err != nil {
|
||||
Error(logger, w, r, err)
|
||||
return
|
||||
}
|
||||
NoContent(w)
|
||||
}
|
||||
}
|
||||
20
httputil/handler_func.go
Normal file
20
httputil/handler_func.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package httputil
|
||||
|
||||
import "net/http"
|
||||
|
||||
var _ http.Handler = HandlerFunc(nil)
|
||||
|
||||
// HandlerFunc is an http.Handler that returns an error.
|
||||
// On non-nil error the error is mapped to the appropriate HTTP response via [Error].
|
||||
// Use for manual handlers that need path parameters or custom status codes.
|
||||
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
|
||||
|
||||
// ServeHTTP implements http.Handler.
|
||||
// Errors are written as standardized JSON without logging — no logger is in
|
||||
// scope for a bare function type. Use [Handle], [HandleNoBody], or
|
||||
// [HandleEmpty] for centralized logging, or call [Error] explicitly.
|
||||
func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if err := h(w, r); err != nil {
|
||||
writeError(w, err)
|
||||
}
|
||||
}
|
||||
119
httputil/response.go
Normal file
119
httputil/response.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package httputil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||
)
|
||||
|
||||
// JSON encodes v as JSON and writes it with the given status code.
|
||||
// Sets Content-Type: application/json.
|
||||
func JSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// NoContent writes a 204 No Content response.
|
||||
func NoContent(w http.ResponseWriter) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// Error is the centralized error handler. It logs at the appropriate level and
|
||||
// writes a standardized JSON error body.
|
||||
//
|
||||
// Log level is derived from the HTTP status:
|
||||
// - 5xx → Error (unexpected server failure; logz auto-enriches with error_code and context fields)
|
||||
// - 4xx → Warn (client mistake — not a server failure)
|
||||
// - 499 → Info (client cancelled the request intentionally)
|
||||
//
|
||||
// The response body always contains code and message; platform_code and context
|
||||
// fields attached via [xerrors.Err.WithContext] are included when present.
|
||||
func Error(logger logging.Logger, w http.ResponseWriter, r *http.Request, err error) {
|
||||
reqLogger := logger.WithContext(r.Context())
|
||||
|
||||
var xe *xerrors.Err
|
||||
switch {
|
||||
case err == nil:
|
||||
reqLogger.Error("handler error", xerrors.Internal("nil error passed to httputil.Error"))
|
||||
case errors.As(err, &xe):
|
||||
status := codeToStatus(xe.Code())
|
||||
switch {
|
||||
case status >= 500:
|
||||
reqLogger.Error("handler error", err)
|
||||
case status == 499:
|
||||
reqLogger.Info("handler: request cancelled", "error_code", string(xe.Code()))
|
||||
default:
|
||||
args := []any{"error_code", string(xe.Code()), "status", status}
|
||||
for k, v := range xe.Fields() {
|
||||
args = append(args, k, v)
|
||||
}
|
||||
reqLogger.Warn("handler error", args...)
|
||||
}
|
||||
default:
|
||||
reqLogger.Error("handler error", err)
|
||||
}
|
||||
|
||||
writeError(w, err)
|
||||
}
|
||||
|
||||
// writeError writes the HTTP error response without logging.
|
||||
// Used by [HandlerFunc].ServeHTTP where no logger is in scope.
|
||||
func writeError(w http.ResponseWriter, err error) {
|
||||
var xe *xerrors.Err
|
||||
if errors.As(err, &xe) {
|
||||
JSON(w, codeToStatus(xe.Code()), errorBody(string(xe.Code()), xe.PlatformCode(), xe.Message(), xe.Fields()))
|
||||
return
|
||||
}
|
||||
JSON(w, http.StatusInternalServerError, errorBody("INTERNAL", "", "internal server error", nil))
|
||||
}
|
||||
|
||||
func errorBody(code, platformCode, message string, fields map[string]any) map[string]any {
|
||||
m := map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
}
|
||||
if platformCode != "" {
|
||||
m["platform_code"] = platformCode
|
||||
}
|
||||
for k, v := range fields {
|
||||
m[k] = v
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func codeToStatus(code xerrors.Code) int {
|
||||
switch code {
|
||||
case xerrors.ErrInvalidInput, xerrors.ErrOutOfRange:
|
||||
return http.StatusBadRequest
|
||||
case xerrors.ErrUnauthorized:
|
||||
return http.StatusUnauthorized
|
||||
case xerrors.ErrPermissionDenied:
|
||||
return http.StatusForbidden
|
||||
case xerrors.ErrNotFound:
|
||||
return http.StatusNotFound
|
||||
case xerrors.ErrAlreadyExists, xerrors.ErrAborted:
|
||||
return http.StatusConflict
|
||||
case xerrors.ErrGone:
|
||||
return http.StatusGone
|
||||
case xerrors.ErrPreconditionFailed:
|
||||
return http.StatusPreconditionFailed
|
||||
case xerrors.ErrRateLimited:
|
||||
return http.StatusTooManyRequests
|
||||
case xerrors.ErrCancelled:
|
||||
return 499
|
||||
case xerrors.ErrInternal, xerrors.ErrDataLoss:
|
||||
return http.StatusInternalServerError
|
||||
case xerrors.ErrNotImplemented:
|
||||
return http.StatusNotImplemented
|
||||
case xerrors.ErrUnavailable:
|
||||
return http.StatusServiceUnavailable
|
||||
case xerrors.ErrDeadlineExceeded:
|
||||
return http.StatusGatewayTimeout
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user