diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 1d16169..dfba583 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -16,7 +16,8 @@ jobs: - name: Set up Go uses: actions/setup-go@v3 with: - go-version: 1.17 + go-version: 1.21 + cache: false - name: Build run: go build -v ./... @@ -25,7 +26,9 @@ jobs: run: go test -v -race ./... - name: golangci-lint - uses: golangci/golangci-lint-action@v3.1.0 + uses: golangci/golangci-lint-action@v3 + with: + version: v1.54 - name: Coverage run: go test -v ./... -coverprofile=coverage.txt -covermode=atomic diff --git a/balancer/round_robin.go b/balancer/round_robin.go index 9c6b1ea..8f48fc5 100644 --- a/balancer/round_robin.go +++ b/balancer/round_robin.go @@ -4,10 +4,12 @@ package balancer +import "sync/atomic" + //RoundRobin will select the server in turn from the server to proxy type RoundRobin struct { BaseBalancer - i uint64 + i atomic.Uint64 } func init() { @@ -17,7 +19,7 @@ func init() { // NewRoundRobin create new RoundRobin balancer func NewRoundRobin(hosts []string) Balancer { return &RoundRobin{ - i: 0, + i: atomic.Uint64{}, BaseBalancer: BaseBalancer{ hosts: hosts, }, @@ -31,7 +33,6 @@ func (r *RoundRobin) Balance(_ string) (string, error) { if len(r.hosts) == 0 { return "", NoHostError } - host := r.hosts[r.i%uint64(len(r.hosts))] - r.i++ + host := r.hosts[r.i.Add(1)%uint64(len(r.hosts))] return host, nil } diff --git a/balancer/round_roubin_test.go b/balancer/round_roubin_test.go index ed18f05..7923519 100644 --- a/balancer/round_roubin_test.go +++ b/balancer/round_roubin_test.go @@ -5,6 +5,7 @@ package balancer import ( + "sync/atomic" "testing" "github.com/stretchr/testify/assert" @@ -28,7 +29,7 @@ func TestRoundRobin_Add(t *testing.T) { hosts: []string{"http://127.0.0.1:1011", "http://127.0.0.1:1012", "http://127.0.0.1:1013"}, }, - i: 0, + i: atomic.Uint64{}, }, }, { @@ -41,7 +42,7 @@ func TestRoundRobin_Add(t *testing.T) { hosts: []string{"http://127.0.0.1:1011", "http://127.0.0.1:1012"}, }, - i: 0, + i: atomic.Uint64{}, }, }, } diff --git a/go.mod b/go.mod index 868ae0e..6a1eb8e 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/zehuamama/balancer -go 1.17 +go 1.21 require ( github.com/gorilla/mux v1.8.0