From d6f40ac5b7b7eb1560f517d17ecd21727064a9ea Mon Sep 17 00:00:00 2001 From: kinggo Date: Fri, 14 Oct 2022 01:52:11 +0800 Subject: [PATCH] fix: solve data race in middleware/proxy's test --- middleware/proxy/proxy.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/middleware/proxy/proxy.go b/middleware/proxy/proxy.go index e9c3af823c..a468f41b8b 100644 --- a/middleware/proxy/proxy.go +++ b/middleware/proxy/proxy.go @@ -6,6 +6,7 @@ import ( "fmt" "net/url" "strings" + "sync" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/utils" @@ -107,6 +108,8 @@ var client = &fasthttp.Client{ DisablePathNormalizing: true, } +var lock sync.RWMutex + // WithTlsConfig update http client with a user specified tls.config // This function should be called before Do and Forward. // Deprecated: use WithClient instead. @@ -117,6 +120,8 @@ func WithTlsConfig(tlsConfig *tls.Config) { // WithClient sets the global proxy client. // This function should be called before Do and Forward. func WithClient(cli *fasthttp.Client) { + lock.Lock() + defer lock.Unlock() client = cli } @@ -137,7 +142,9 @@ func Do(c *fiber.Ctx, addr string, clients ...*fasthttp.Client) error { cli = clients[0] } else { // Set global client + lock.RLock() cli = client + lock.RUnlock() } req := c.Request() res := c.Response()