fix(06-12): bound named middleware by body cap, cache factories, fail boot on bad body config and mux conflicts

This commit is contained in:
Jakub Zych
2026-09-21 19:42:20 +02:00
parent 46c7e4f98e
commit a50e09ba34
3 changed files with 118 additions and 7 deletions

View File

@@ -125,3 +125,57 @@ func (p bodyEchoPlugin) Routes(r pact.Router) error {
})
return nil
}
type mwReadPlugin struct{ seen *error }
func (p mwReadPlugin) ID() string { return "golem15.mwread" }
func (p mwReadPlugin) Requires() []string { return nil }
func (p mwReadPlugin) Register(*backpack.App) error { return nil }
func (p mwReadPlugin) Boot(*backpack.App) error { return nil }
func (p mwReadPlugin) Middlewares() map[string]pact.Middleware {
return map[string]pact.Middleware{"reader": func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, *p.seen = io.ReadAll(r.Body)
next.ServeHTTP(w, r)
})
}}
}
func (p mwReadPlugin) Routes(r pact.Router) error {
r.Group("/", Use("reader"), func(g pact.Router) {
g.Post("/x", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
})
return nil
}
func TestBodyLimitBoundsNamedMiddleware(t *testing.T) {
cfg := writeHTTPConfig(t, "body_limits:\n default_bytes: 4\n upload_bytes: 8\n")
var seen error
h, err := Assemble(backpack.New(cfg), []party.Plugin{mwReadPlugin{seen: &seen}})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(strings.Repeat("a", 10)))
h.ServeHTTP(httptest.NewRecorder(), req)
var maxErr *http.MaxBytesError
if !errors.As(seen, &maxErr) {
t.Fatalf("middleware read err = %v, want MaxBytesError", seen)
}
}
func TestBodyLimitMissingConfigFailsBoot(t *testing.T) {
cfg := writeHTTPConfig(t, "body_limits:\n upload_bytes: 8\n")
if _, err := BuildRouter(backpack.New(cfg), nil); err == nil || !strings.Contains(err.Error(), "default_bytes") {
t.Fatalf("err = %v", err)
}
}
func TestCompileRouteConflictReturnsError(t *testing.T) {
r := New(nil)
ok := func(w http.ResponseWriter, _ *http.Request) {}
r.BindPlugin("a")
r.Get("/a/{x}", ok)
r.Get("/a/{y}", ok)
if _, err := r.compile(); err == nil {
t.Fatal("expected conflict error")
}
}