Skip to content
Myr

Fix context.Params race condition on Copy() (#1841)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Fix context.Params race condition on Copy() Using context.Param(key) on a context.Copy inside a goroutine may lead to incorrect value on a high load, where another request overwrite a Param * Using waitgroup to wait asynchronous test case

authored by Samuel Abreu · committed by 田欧 · parent 35e33d3 · Browse files · 2 files+26 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+26 added−0 removed

  • other:+26 added−0 removed

2 files+26 added−0 removed

modified:context_test.go+23 added
11 unmodified lines
12 "io"13 "mime/multipart"14 "net/http"15 "net/http/httptest"16 "os"17 "reflect"18 "strings"19 "sync"20 "testing"21 "time"2223 "github.com/gin-contrib/sse"
1798 unmodified lines
1822 assert.NotPanics(t, func() {1823 c.Next()1824 })1825}18261827func TestRaceParamsContextCopy(t *testing.T) {1828 DefaultWriter = os.Stdout1829 router := Default()1830 nameGroup := router.Group("/:name")1831 var wg sync.WaitGroup1832 wg.Add(2)1833 {1834 nameGroup.GET("/api", func(c *Context) {1835 go func(c *Context, param string) {1836 defer wg.Done()1837 // First assert must be executed after the second request1838 time.Sleep(50 * time.Millisecond)1839 assert.Equal(t, c.Param("name"), param)1840 }(c.Copy(), c.Param("name"))1841 })1842 }1843 performRequest(router, "GET", "/name1/api")1844 performRequest(router, "GET", "/name2/api")1845 wg.Wait()1846}
modified:context.go+3 added
87 unmodified lines
88 cp.Keys = map[string]interface{}{}89 for k, v := range c.Keys {90 cp.Keys[k] = v91 }92 paramCopy := make([]Param, len(cp.Params))93 copy(paramCopy, cp.Params)94 cp.Params = paramCopy95 return &cp96}9798// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",
939 unmodified lines