From de5a5dc96ec9369768ed9b4e72d428feecc05c92 Mon Sep 17 00:00:00 2001 From: Aykhan Shahsuvarov Date: Sat, 14 Sep 2024 20:06:32 +0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A8=20Select=20client=20with=20random?= =?UTF-8?q?=20indexes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requests/client.go | 23 +++++++++++------------ requests/request.go | 2 +- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/requests/client.go b/requests/client.go index a0fe0ff..fc5c75f 100644 --- a/requests/client.go +++ b/requests/client.go @@ -3,6 +3,7 @@ package requests import ( "context" "fmt" + "math/rand" "net/url" "sync" "time" @@ -276,24 +277,22 @@ func getDialFunc(proxy *config.Proxy, timeout time.Duration) (fasthttp.DialFunc, return dialer, nil } -// getSharedClientFuncMultiple returns a ClientGeneratorFunc that cycles through -// a provided list of fasthttp.HostClient instances. Each call to the returned -// function will return the next client in the list, cycling back to the first -// client after reaching the end of the slice. -// -// The returned function isn't thread-safe and should be used in a single-threaded context. -func getSharedClientFuncMultiple(clients []*fasthttp.HostClient) ClientGeneratorFunc { +// getSharedClientFuncMultiple returns a ClientGeneratorFunc that cycles through a list of fasthttp.HostClient instances. +// The function uses a local random number generator to determine the starting index and stop index for cycling through the clients. +func getSharedClientFuncMultiple(clients []*fasthttp.HostClient, localRand *rand.Rand) ClientGeneratorFunc { var ( - currentIndex int = 0 clientsCount int = len(clients) + currentIndex int = localRand.Intn(clientsCount) + stopIndex int = clientsCount ) return func() *fasthttp.HostClient { - client := clients[currentIndex] - if currentIndex == clientsCount-1 { - currentIndex = 0 + client := clients[currentIndex%clientsCount] + if currentIndex == stopIndex { + currentIndex = localRand.Intn(clientsCount) + stopIndex = currentIndex - 1 } else { - currentIndex++ + currentIndex = (currentIndex + 1) % clientsCount } return client diff --git a/requests/request.go b/requests/request.go index 1dcc437..b36b449 100644 --- a/requests/request.go +++ b/requests/request.go @@ -69,7 +69,7 @@ func newRequest( if clientsCount == 1 { getClient = getSharedClientFuncSingle(clients[0]) } else { - getClient = getSharedClientFuncMultiple(clients) + getClient = getSharedClientFuncMultiple(clients, localRand) } getRequest := getRequestGeneratorFunc(