-
Notifications
You must be signed in to change notification settings - Fork 0
/
filters.go
81 lines (70 loc) · 1.48 KB
/
filters.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package registry
import (
"os"
"github.com/sirupsen/logrus"
)
// Filter used for filtering service
// do not return nil
// Ex Load Balancing
type Filter func(services []*Pong) []*Pong
// ObserveFilter used to accept (or not) new registered service.
//
// Ex: you want only service on same host
type ObserveFilter func(s *Pong) bool
func hostname() string {
host, err := os.Hostname()
if err != nil {
logrus.Error("Unable to get local hostname: ", err.Error())
}
return host
}
// LocalhostFilter return true if hostname is equals to service host
func LocalhostFilter() Filter {
host := hostname()
fn := func(services []*Pong) []*Pong {
res := []*Pong{}
for _, s := range services {
if s.Host == host {
res = append(res, s)
}
}
return res
}
return fn
}
// LoadBalanceFilter basic loadbalancer
func LoadBalanceFilter() Filter {
lastInd := -1
emptyServices := []*Pong{}
fn := func(services []*Pong) []*Pong {
lastInd++
size := len(services)
if size == 0 {
return emptyServices
}
if lastInd >= size {
lastInd = 0
}
return []*Pong{services[lastInd]}
}
return fn
}
func PassingFilter() Filter {
fn := func(services []*Pong) []*Pong {
res := []*Pong{}
for _, p := range services {
if p.Status == Passing {
res = append(res, p)
}
}
return res
}
return fn
}
// LocalhostOFilter accept only service on the same machine
func LocalhostOFilter() ObserveFilter {
name := hostname()
return func(p *Pong) bool {
return name == p.Host
}
}