Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support adding/removing clients from LBClient #1243

Merged
merged 8 commits into from Apr 1, 2022
27 changes: 27 additions & 0 deletions lbclient.go
Expand Up @@ -50,6 +50,7 @@ type LBClient struct {
cs []*lbClient

once sync.Once
mu sync.Mutex
}

// DefaultLBClientTimeout is the default request timeout used by LBClient
Expand Down Expand Up @@ -91,6 +92,32 @@ func (cc *LBClient) init() {
}
}

// AddClient adds a new client to the balanced clients
// returns the new total number of clients
func (cc *LBClient) AddClient(c BalancingClient) int {
cc.mu.Lock()
cc.cs = append(cc.cs, &lbClient{
c: c,
healthCheck: cc.HealthCheck,
})
cc.mu.Unlock()
return len(cc.cs)
}

// RemoveClients removes clients using the provided callback
// if rc returns true, the passed client will be removed
// returns the new total number of clients
func (cc *LBClient) RemoveClients(rc func(BalancingClient) bool) int {
cc.mu.Lock()
for idx, cs := range cc.cs {
if rc(cs.c) {
cc.cs = append(cc.cs[:idx], cc.cs[idx+1])
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a correct way to filter a slice. See: https://go.dev/play/p/9y9DyCJ_xDD

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, my bad. addressed

}
}
cc.mu.Unlock()
return len(cc.cs)
}

func (cc *LBClient) get() *lbClient {
cc.once.Do(cc.init)

Expand Down