forked from segmentio/nsq-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topology.go
50 lines (42 loc) · 1.19 KB
/
topology.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
package nsqlookup
import (
"context"
"net"
)
// Toppology is an interface abstracting the discovery of network topology.
type Topology interface {
LookupIPZone(ctx context.Context, ip net.IP) (zone string, err error)
}
// Subnet represents a network subnet, which is made of a CIDR for the range of
// IP addresses it contains, and a logical zone name.
type Subnet struct {
CIDR *net.IPNet
Zone string
}
// SubnetTopology is an implementation of the Topology interface working on a
// static list of subnets.
type SubnetTopology []Subnet
func (topology SubnetTopology) LookupIPZone(ctx context.Context, ip net.IP) (zone string, err error) {
for _, subnet := range topology {
if subnet.CIDR.Contains(ip) {
zone = subnet.Zone
break
}
}
err = ctx.Err()
return
}
// WithClientIP returns a context which carries the given client IP.
func WithClientIP(ctx context.Context, ip net.IP) context.Context {
if ip == nil {
return ctx
}
return context.WithValue(ctx, clientIPKey{}, ip)
}
// ClientIP returns the client IP embedded in the context, or nil if none were
// found.
func ClientIP(ctx context.Context) net.IP {
ip, _ := ctx.Value(clientIPKey{}).(net.IP)
return ip
}
type clientIPKey struct{}