/
consul.go
39 lines (33 loc) · 830 Bytes
/
consul.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
package main
import (
"net/url"
"encoding/json"
"github.com/armon/consul-api"
)
type ConsulRegistry struct {
client *consulapi.Client
path string
}
func NewConsulRegistry(uri *url.URL) ServiceRegistry {
config := consulapi.DefaultConfig()
if uri.Host != "" {
config.Address = uri.Host
}
client, err := consulapi.NewClient(config)
assert(err)
return &ConsulRegistry{client: client, path: uri.Path}
}
func (r *ConsulRegistry) Register(job *Job) error {
path := r.path[1:] + "/" + job.ID
jsonBytes, jsonerr := json.Marshal(job)
if jsonerr != nil {
return jsonerr
}
_, err := r.client.KV().Put(&consulapi.KVPair{Key: path, Value: jsonBytes}, nil)
return err
}
func (r *ConsulRegistry) Deregister(job *Job) error {
path := r.path[1:] + "/" + job.ID
_, err := r.client.KV().Delete(path, nil)
return err
}