-
Notifications
You must be signed in to change notification settings - Fork 14
/
round_robin.go
37 lines (30 loc) · 726 Bytes
/
round_robin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package roundrobin
import (
"errors"
"net/url"
"sync/atomic"
)
// ErrServersNotExists is the error that servers dose not exists
var ErrServersNotExists = errors.New("servers dose not exist")
// RoundRobin is an interface for representing round-robin balancing.
type RoundRobin interface {
Next() *url.URL
}
type roundrobin struct {
urls []*url.URL
next uint32
}
// New returns RoundRobin implementation(*roundrobin).
func New(urls ...*url.URL) (RoundRobin, error) {
if len(urls) == 0 {
return nil, ErrServersNotExists
}
return &roundrobin{
urls: urls,
}, nil
}
// Next returns next address
func (r *roundrobin) Next() *url.URL {
n := atomic.AddUint32(&r.next, 1)
return r.urls[(int(n)-1)%len(r.urls)]
}