-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdiscover.go
42 lines (35 loc) · 949 Bytes
/
discover.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
package main
import (
"fmt"
log "github.com/Sirupsen/logrus"
consul "github.com/hashicorp/consul/api"
)
type discoveryRecord struct {
name string
tag string
discoveredHosts []string
}
func NewDiscovery(client *consul.Client, name string, tag string) *discoveryRecord {
rec := &discoveryRecord{
name: name,
tag: tag,
discoveredHosts: []string{},
}
discover(client, rec)
return rec
}
func discover(client *consul.Client, r *discoveryRecord) {
services, _, err := client.Catalog().Service(r.name, r.tag, nil)
if err != nil {
log.Warnf("Couldn't get %s services from consul: %v", r.name, err)
}
var hosts []string
for _, svc := range services {
host := svc.Node
port := svc.ServicePort
location := fmt.Sprintf("%s:%d", host, port)
hosts = append(hosts, location)
}
r.discoveredHosts = hosts
log.Debugf("Discovered %s service hosts: %v", r.name, r.discoveredHosts)
}