Skip to content

Instantly share code, notes, and snippets.

@kasvith
Created November 9, 2019 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasvith/7e3efccd3e26615654106265b1ce43f4 to your computer and use it in GitHub Desktop.
Save kasvith/7e3efccd3e26615654106265b1ce43f4 to your computer and use it in GitHub Desktop.
// GetNextPeer returns next active peer to take a connection
func (s *ServerPool) GetNextPeer() *Backend {
// loop entire backends to find out an Alive backend
next := s.NextIndex()
l := len(s.backends) + next // start from next and move a full cycle
for i := next; i < l; i++ {
idx := i % len(s.backends) // take an index by modding
if s.backends[idx].IsAlive() { // if we have an alive backend, use it and store if its not the original one
if i != next {
atomic.StoreUint64(&s.current, uint64(idx))
}
return s.backends[idx]
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment