-
Notifications
You must be signed in to change notification settings - Fork 9
/
random.go
47 lines (36 loc) · 809 Bytes
/
random.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
38
39
40
41
42
43
44
45
46
47
package random
import (
"fmt"
"math/rand"
"github.com/benschw/srv-lb/dns"
"github.com/benschw/srv-lb/lb"
)
const RandomStrategy lb.StrategyType = "random"
func New(lib dns.Lookup) lb.GenericLoadBalancer {
lb := new(RandomClb)
lb.dnsLib = lib
return lb
}
type RandomClb struct {
dnsLib dns.Lookup
}
func (lb *RandomClb) Next(name string) (dns.Address, error) {
add := dns.Address{}
srvs, err := lb.dnsLib.LookupSRV(name)
if err != nil {
return add, err
}
if len(srvs) == 0 {
return add, fmt.Errorf("no SRV records found")
}
// log.Printf("%+v", srvs)
srv := srvs[rand.Intn(len(srvs))]
ip, err := lb.dnsLib.LookupA(srv.Target)
if err != nil {
return add, err
}
return dns.Address{Address: ip, Port: srv.Port}, nil
}
func init() {
lb.RegisterStrategy(RandomStrategy, New)
}