1 Commits
8 changed files with 217 additions and 23 deletions
+21
View File
@@ -6,6 +6,27 @@ This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html
--- ---
## [1.5.0] — 2026-08-09
Minor — configurable success status on the httputil handler adapters.
### Added
- **`httputil.WithStatus(code int) Option`** and variadic `opts ...Option` on `Handle`,
`HandleNoBody` and `HandleEmpty`. Override the success status — e.g. `WithStatus(201)` on a
resource-creating POST, `WithStatus(202)` on an async `HandleEmpty`. Non-breaking: existing
calls keep their defaults (200 / 200 / 204).
### Changed
- Bumped `contracts`, `core` to v1.5.0.
### Notes
- `WithStatus` is success-only: the adapters own only the happy path, so the code must be 2xx.
A non-2xx code panics at wiring (the service fails to boot) rather than emitting a wrong
status at runtime. Error status stays separate — resolved from the returned xerror by `Error`.
## [1.4.0] — 2026-08-09 ## [1.4.0] — 2026-08-09
Minor — resolvable request IDs, plus a dependency refresh. Minor — resolvable request IDs, plus a dependency refresh.
+15 -8
View File
@@ -1,6 +1,6 @@
# einherjar/web # einherjar/web
[![version](https://img.shields.io/badge/version-v1.4.0-5C4EE5?style=flat-square)](https://code.nochebuena.dev/einherjar/web) [![version](https://img.shields.io/badge/version-v1.5.0-5C4EE5?style=flat-square)](https://code.nochebuena.dev/einherjar/web)
[![license](https://img.shields.io/badge/license-AGPL--3.0-22863A?style=flat-square)](LICENSE) [![license](https://img.shields.io/badge/license-AGPL--3.0-22863A?style=flat-square)](LICENSE)
[![go](https://img.shields.io/badge/Go-1.26+-00ADD8?style=flat-square&logo=go&logoColor=white)](https://go.dev) [![go](https://img.shields.io/badge/Go-1.26+-00ADD8?style=flat-square&logo=go&logoColor=white)](https://go.dev)
@@ -150,26 +150,33 @@ type CreateUserRes struct {
v := valid.New() v := valid.New()
// POST /users — decode body → validate → call service → encode response // POST /users — decode → validate → call → encode. WithStatus makes it 201 Created.
srv.Post("/users", httputil.Handle(v, func(ctx context.Context, req CreateUserReq) (CreateUserRes, error) { srv.Post("/users", httputil.Handle(v, logger, func(ctx context.Context, req CreateUserReq) (CreateUserRes, error) {
id, err := userService.Create(ctx, req.Email, req.Name) id, err := userService.Create(ctx, req.Email, req.Name)
if err != nil { if err != nil {
return CreateUserRes{}, err return CreateUserRes{}, err
} }
return CreateUserRes{ID: id}, nil return CreateUserRes{ID: id}, nil
})) }, httputil.WithStatus(http.StatusCreated)))
// GET /users/{id} — no request body // GET /users/{id} — no request body (defaults to 200)
srv.Get("/users/{id}", httputil.HandleNoBody(func(ctx context.Context) (CreateUserRes, error) { srv.Get("/users/{id}", httputil.HandleNoBody(logger, func(ctx context.Context) (CreateUserRes, error) {
// ... // ...
})) }))
// DELETE /users/{id} — no response body // DELETE /users/{id} — no response body (defaults to 204)
srv.Delete("/users/{id}", httputil.HandleEmpty(v, func(ctx context.Context, req DeleteReq) error { srv.Delete("/users/{id}", httputil.HandleEmpty(v, logger, func(ctx context.Context, req DeleteReq) error {
return userService.Delete(ctx, req.ID) return userService.Delete(ctx, req.ID)
})) }))
``` ```
**Success status** defaults to 200 for the body-returning adapters and 204 for `HandleEmpty`;
override it with `httputil.WithStatus(code)` — e.g. `WithStatus(http.StatusCreated)` on a POST, or
`WithStatus(http.StatusAccepted)` for an async `HandleEmpty`. The code must be 2xx (these adapters
own only the success path); a non-2xx code panics at wiring, so the service fails to start rather
than emit a wrong status at runtime. **Error status is separate** — return the right `*xerrors.Err`
and `Error` maps it (full 16-code table below).
Validation failures return 400 with a structured JSON error. All `*xerrors.Err` Validation failures return 400 with a structured JSON error. All `*xerrors.Err`
values are mapped to their canonical HTTP status codes (full 16-code table below). values are mapped to their canonical HTTP status codes (full 16-code table below).
+1
View File
@@ -20,3 +20,4 @@ Decisions worth noting (not ADR-worthy individually):
| `observability.Checkable` not redefined | Imported from contracts | Starters implement contracts directly; no web import needed by db/cache starters | | `observability.Checkable` not redefined | Imported from contracts | Starters implement contracts directly; no web import needed by db/cache starters |
| Background goroutine for in-memory eviction | `time.Ticker` goroutine | Avoids `worker` module dependency; in-memory store is self-contained | | Background goroutine for in-memory eviction | `time.Ticker` goroutine | Avoids `worker` module dependency; in-memory store is self-contained |
| `mw.RequestIDFrom` resolver sees the request (v1.4.0) | New entry point takes `func(*http.Request) string`; `RequestID` becomes a request-ignoring wrapper over it | An inbound correlation id must be able to survive this boundary, but acceptability is per-service — a typed audit column rejects what an opaque log accepts. The framework provides plumbing only (context + header, once per request); the app owns policy (which header, validation, generation fallback). An empty resolver result attaches nothing rather than a silently-empty value | | `mw.RequestIDFrom` resolver sees the request (v1.4.0) | New entry point takes `func(*http.Request) string`; `RequestID` becomes a request-ignoring wrapper over it | An inbound correlation id must be able to survive this boundary, but acceptability is per-service — a typed audit column rejects what an opaque log accepts. The framework provides plumbing only (context + header, once per request); the app owns policy (which header, validation, generation fallback). An empty resolver result attaches nothing rather than a silently-empty value |
| `httputil` success status is configurable (v1.5.0) | `Handle`/`HandleNoBody`/`HandleEmpty` take `opts ...Option`; `WithStatus(code)` overrides the default (200 / 200 / 204) | 201 Created / 202 Accepted are common and were only reachable by hand-rolling the handler (losing decode+validate+error-mapping). Variadic options are non-breaking and future-extensible (headers, etc.). `WithStatus` is success-only (2xx) and panics at wiring on a non-2xx code — a wrong status is a routing mistake that should fail to boot, not surface at runtime; error status stays separate, resolved from the xerror by `Error` |
+2 -2
View File
@@ -3,8 +3,8 @@ module code.nochebuena.dev/einherjar/web
go 1.26 go 1.26
require ( require (
code.nochebuena.dev/einherjar/contracts v1.4.0 code.nochebuena.dev/einherjar/contracts v1.5.0
code.nochebuena.dev/einherjar/core v1.4.0 code.nochebuena.dev/einherjar/core v1.5.0
github.com/go-chi/chi/v5 v5.3.1 github.com/go-chi/chi/v5 v5.3.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
golang.org/x/time v0.15.0 golang.org/x/time v0.15.0
+4 -4
View File
@@ -1,7 +1,7 @@
code.nochebuena.dev/einherjar/contracts v1.4.0 h1:rv/93dGXmXvO90G0uxCu8y3+5+EobkVvcoxh/BywIFk= code.nochebuena.dev/einherjar/contracts v1.5.0 h1:vDlpLXtVZ4Q4l3AR02qLQhnKnEDq2vE8+mydwg85hUU=
code.nochebuena.dev/einherjar/contracts v1.4.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI= code.nochebuena.dev/einherjar/contracts v1.5.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
code.nochebuena.dev/einherjar/core v1.4.0 h1:YBRFzgeWNh8BCHueNYGo+V754BjzvJvq2CddJcc5ZjQ= code.nochebuena.dev/einherjar/core v1.5.0 h1:LXVyHaite+NHL8LIGj/NvCVqgCrkpVMfm2VaIZ9aAU8=
code.nochebuena.dev/einherjar/core v1.4.0/go.mod h1:dILfAATF++TBeLOwUTQsYci+Ft7yK5ivt00iRYctfGk= code.nochebuena.dev/einherjar/core v1.5.0/go.mod h1:lxiRdCVLl1/XnbCsHbeZJIFNXZ29QaSl2lMGZm3CQjM=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
+16 -9
View File
@@ -14,9 +14,11 @@ import (
// - Decodes the JSON request body into Req. // - Decodes the JSON request body into Req.
// - Validates Req using the provided [valid.Validator]. // - Validates Req using the provided [valid.Validator].
// - Calls fn with the request context and decoded Req. // - Calls fn with the request context and decoded Req.
// - Encodes Res as JSON with HTTP 200 on success. // - Encodes Res as JSON on success — HTTP 200 by default, or the code given via
// [WithStatus] (e.g. WithStatus(http.StatusCreated) for a resource-creating POST).
// - On error: logs via [Error] (level derived from HTTP status) and writes the standardized JSON body. // - 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 { func Handle[Req, Res any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) (Res, error), opts ...Option) http.HandlerFunc {
status := resolveStatus(http.StatusOK, opts)
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var req Req var req Req
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -32,28 +34,33 @@ func Handle[Req, Res any](v valid.Validator, logger logging.Logger, fn func(ctx
Error(logger, w, r, err) Error(logger, w, r, err)
return return
} }
JSON(w, http.StatusOK, res) JSON(w, status, res)
} }
} }
// HandleNoBody adapts a typed function with no request body (GET, HEAD). // 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. // Calls fn with the request context; encodes the result as JSON HTTP 200 by
// default, or the code given via [WithStatus].
// On error: logs via [Error] and writes the standardized JSON body. // 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 { func HandleNoBody[Res any](logger logging.Logger, fn func(ctx context.Context) (Res, error), opts ...Option) http.HandlerFunc {
status := resolveStatus(http.StatusOK, opts)
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
res, err := fn(r.Context()) res, err := fn(r.Context())
if err != nil { if err != nil {
Error(logger, w, r, err) Error(logger, w, r, err)
return return
} }
JSON(w, http.StatusOK, res) JSON(w, status, res)
} }
} }
// HandleEmpty adapts a typed function with a request body but no response body. // 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. // Decodes and validates Req, calls fn, and writes a body-less success — 204 No
// Content by default, or the code given via [WithStatus] (e.g.
// WithStatus(http.StatusAccepted) for async processing).
// On error: logs via [Error] and writes the standardized JSON body. // 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 { func HandleEmpty[Req any](v valid.Validator, logger logging.Logger, fn func(ctx context.Context, req Req) error, opts ...Option) http.HandlerFunc {
status := resolveStatus(http.StatusNoContent, opts)
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var req Req var req Req
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -68,6 +75,6 @@ func HandleEmpty[Req any](v valid.Validator, logger logging.Logger, fn func(ctx
Error(logger, w, r, err) Error(logger, w, r, err)
return return
} }
NoContent(w) w.WriteHeader(status)
} }
} }
+118
View File
@@ -0,0 +1,118 @@
package httputil
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"code.nochebuena.dev/einherjar/contracts/logging"
"code.nochebuena.dev/einherjar/core/logz"
"code.nochebuena.dev/einherjar/core/valid"
)
type tReq struct {
Name string `json:"name" validate:"required"`
}
type tRes struct {
ID string `json:"id"`
}
func discardLogger() logging.Logger { return logz.New(logz.Config{Writer: io.Discard}) }
// Default: Handle writes 200 with the JSON payload (regression — no opts).
func TestHandle_Default200(t *testing.T) {
h := Handle(valid.New(), discardLogger(), func(context.Context, tReq) (tRes, error) {
return tRes{ID: "x"}, nil
})
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if got := strings.TrimSpace(rec.Body.String()); got != `{"id":"x"}` {
t.Errorf("body = %q, want {\"id\":\"x\"}", got)
}
}
// WithStatus(201) makes a resource-creating Handle return 201 Created + the body.
func TestHandle_WithStatusCreated(t *testing.T) {
h := Handle(valid.New(), discardLogger(), func(context.Context, tReq) (tRes, error) {
return tRes{ID: "x"}, nil
}, WithStatus(http.StatusCreated))
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201", rec.Code)
}
if got := strings.TrimSpace(rec.Body.String()); got != `{"id":"x"}` {
t.Errorf("body = %q, want the payload", got)
}
}
func TestHandleNoBody_WithStatus(t *testing.T) {
h := HandleNoBody(discardLogger(), func(context.Context) (tRes, error) {
return tRes{ID: "y"}, nil
}, WithStatus(http.StatusAccepted))
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", rec.Code)
}
}
// Default: HandleEmpty writes 204 with no body.
func TestHandleEmpty_Default204(t *testing.T) {
h := HandleEmpty(valid.New(), discardLogger(), func(context.Context, tReq) error { return nil })
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204", rec.Code)
}
if rec.Body.Len() != 0 {
t.Errorf("expected empty body, got %q", rec.Body.String())
}
}
// WithStatus on a body-less adapter changes the code but keeps the empty body.
func TestHandleEmpty_WithStatusAccepted_NoBody(t *testing.T) {
h := HandleEmpty(valid.New(), discardLogger(), func(context.Context, tReq) error { return nil }, WithStatus(http.StatusAccepted))
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"a"}`)))
if rec.Code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", rec.Code)
}
if rec.Body.Len() != 0 {
t.Errorf("expected empty body, got %q", rec.Body.String())
}
}
// A non-2xx code is a wiring mistake: WithStatus panics at construction so the
// service fails to boot rather than emitting a wrong status at request time.
func TestWithStatus_PanicsOnNon2xx(t *testing.T) {
for _, code := range []int{0, 100, 199, 300, 404, 500, 1000} {
func() {
defer func() {
if recover() == nil {
t.Errorf("WithStatus(%d) did not panic", code)
}
}()
_ = WithStatus(code)
}()
}
}
func TestWithStatus_Allows2xx(t *testing.T) {
for _, code := range []int{200, 201, 202, 204, 299} {
func() {
defer func() {
if r := recover(); r != nil {
t.Errorf("WithStatus(%d) panicked: %v", code, r)
}
}()
_ = WithStatus(code)
}()
}
}
+40
View File
@@ -0,0 +1,40 @@
package httputil
import "fmt"
// Option configures a Handle* adapter. With no options each adapter writes its
// default success status (200 for the body-returning adapters, 204 for
// [HandleEmpty]). Options are applied once at wiring time, not per request.
type Option func(*options)
type options struct {
status int
}
// WithStatus overrides the success status an adapter writes — e.g.
// WithStatus(http.StatusCreated) for a POST that creates a resource, or
// WithStatus(http.StatusAccepted) for an async [HandleEmpty].
//
// It exists because the Handle* adapters own only the happy path: they always
// write a success response, so the status is theirs to set, while error statuses
// are derived separately from the returned xerror by [Error]. The code must
// therefore be 2xx — anything else is a routing mistake, since an error status
// never belongs on the success path. WithStatus panics on a non-2xx code, and
// because routes are wired at startup that panic surfaces at boot: the service
// fails to start rather than emitting a wrong status at request time. (mw.Recover
// guards requests, so it does not catch a wiring-time panic — which is the point.)
func WithStatus(code int) Option {
if code < 200 || code > 299 {
panic(fmt.Sprintf("httputil.WithStatus: success status must be 2xx, got %d", code))
}
return func(o *options) { o.status = code }
}
// resolveStatus folds opts over the adapter's default success status.
func resolveStatus(def int, opts []Option) int {
o := options{status: def}
for _, opt := range opts {
opt(&o)
}
return o.status
}