From 1bd0ecf2d3e08da37efa270bb7be20c1eddb0d68 Mon Sep 17 00:00:00 2001 From: HazyLab Date: Fri, 25 Sep 2026 08:01:37 +0200 Subject: [PATCH] fix(context): load Keys under the mutex in Copy (#4854) Copy read c.Keys before RLock. Set stores that field under Lock when the map is created. The race detector reports the unsynchronized access, and the copy can observe a nil header and drop keys Set has already published. maps.Clone(nil) returns nil, so the load and the clone belong in the same critical section. Map iteration was already under the mutex. Co-authored-by: hazyhaar --- context.go | 3 +-- context_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/context.go b/context.go index 788b00bb..a6add8a6 100644 --- a/context.go +++ b/context.go @@ -132,9 +132,8 @@ func (c *Context) Copy() *Context { cp.handlers = nil cp.fullPath = c.fullPath - cKeys := c.Keys c.mu.RLock() - cp.Keys = maps.Clone(cKeys) + cp.Keys = maps.Clone(c.Keys) c.mu.RUnlock() cParams := c.Params diff --git a/context_test.go b/context_test.go index cef488c9..b82e04d5 100644 --- a/context_test.go +++ b/context_test.go @@ -709,6 +709,30 @@ func TestContextGetStringMapStringSlice(t *testing.T) { assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"]) } +func TestCopyConcurrentWithSet(t *testing.T) { + c := &Context{} + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + c.Set(i, i) + } + }() + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + cp := c.Copy() + for k, v := range cp.Keys { + if k != v { + t.Errorf("copied key %v = %v, want %v", k, v, k) + } + } + } + }() + wg.Wait() +} + func TestContextCopy(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.index = 2