diff --git a/context.go b/context.go index f71d635e2..7c06d26c0 100644 --- a/context.go +++ b/context.go @@ -676,6 +676,7 @@ func (ctx *Context) WithValue(key, value any) Context { ancestry: ctx.ancestry, cleanupFuncs: ctx.cleanupFuncs, exitFuncs: ctx.exitFuncs, + metricsRegistry: ctx.metricsRegistry, } } diff --git a/context_test.go b/context_test.go index 27395612c..1c1e2e062 100644 --- a/context_test.go +++ b/context_test.go @@ -15,10 +15,28 @@ package caddy import ( + "context" "encoding/json" "io" + "testing" ) +func TestContextWithValuePreservesMetricsRegistry(t *testing.T) { + ctx, cancel := NewContext(Context{Context: context.Background()}) + t.Cleanup(cancel) + + reg := ctx.GetMetricsRegistry() + if reg == nil { + t.Fatal("expected a metrics registry on the base context") + } + + type testKey struct{} + derived := ctx.WithValue(testKey{}, "value") + if got := derived.GetMetricsRegistry(); got != reg { + t.Fatalf("WithValue must preserve the metrics registry: got %p, want %p", got, reg) + } +} + func ExampleContext_LoadModule() { // this whole first part is just setting up for the example; // note the struct tags - very important; we specify inline_key