-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupsteams.go
65 lines (50 loc) · 1.39 KB
/
upsteams.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"time"
)
var DynamicUpstreams map[string]Upstream
type LoadBalancer struct {
last int
max int
loop *[]string
}
// GetUpstream returns the next upstream from list of upstreams
// in a LoadBalancer. Simple RoundRobin.
func (lb *LoadBalancer) GetHost() string {
hostNum := lb.last + 1
if hostNum == lb.max {
hostNum = 0
}
lb.last = hostNum
return (*lb.loop)[hostNum]
}
// SetDynamicUpstreams is function which reads upstreams from config file
// and sets DynamicUpstreams struct used by loadbalancer.
func SetDynamicUpstreams(config *Config, init bool) {
for {
var upstreams = make(map[string]Upstream)
for upstreamName, upstreamConfig := range config.Upstreams {
var hosts []string
var ups = Upstream{}
for _, host := range upstreamConfig.Hosts {
hosts = append(hosts, host)
}
ups.Hosts = hosts
if DynamicUpstreams[upstreamName].LoadBalancer == nil {
var loadbalancer = LoadBalancer{last: 0, max: len(hosts), loop: &ups.Hosts}
ups.LoadBalancer = &loadbalancer // why this work
//DynamicUpstreams[upstreamName].LoadBalancer = &loadbalancer // and this doesn't?
} else {
ups.LoadBalancer = DynamicUpstreams[upstreamName].LoadBalancer
ups.LoadBalancer.max = len(hosts)
}
upstreams[upstreamName] = ups
}
// Set new upstreams
DynamicUpstreams = upstreams
if init == true {
return
}
time.Sleep(5 * time.Second)
}
}