This repository has been archived by the owner on Nov 17, 2021. It is now read-only.
/
poller.go
92 lines (79 loc) · 1.53 KB
/
poller.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
82
83
84
85
86
87
88
89
90
91
92
package binding
import (
"encoding/json"
"log"
"net/http"
"time"
)
type Poller struct {
apiClient client
pollingInterval time.Duration
store Setter
}
type client interface {
Get(int) (*http.Response, error)
}
type Binding struct {
AppID string `json:"app_id"`
Drains []string `json:"drains"`
Hostname string `json:"hostname"`
}
type Setter interface {
Set([]Binding)
}
func NewPoller(ac client, pi time.Duration, s Setter) *Poller {
p := &Poller{
apiClient: ac,
pollingInterval: pi,
store: s,
}
p.poll()
return p
}
func (p *Poller) Poll() {
t := time.NewTicker(p.pollingInterval)
for range t.C {
p.poll()
}
}
func (p *Poller) poll() {
nextID := 0
var bindings []Binding
for {
resp, err := p.apiClient.Get(nextID)
if err != nil {
log.Printf("failed to get id %d from CUPS Provider: %s", nextID, err)
break
}
var aResp apiResponse
err = json.NewDecoder(resp.Body).Decode(&aResp)
if err != nil {
log.Printf("failed to decode JSON: %s", err)
break
}
bindings = append(bindings, p.toBindings(aResp)...)
nextID = aResp.NextID
if nextID == 0 {
break
}
}
p.store.Set(bindings)
}
func (p *Poller) toBindings(aResp apiResponse) []Binding {
var bindings []Binding
for k, v := range aResp.Results {
bindings = append(bindings, Binding{
AppID: k,
Drains: v.Drains,
Hostname: v.Hostname,
})
}
return bindings
}
type apiResponse struct {
Results map[string]struct {
Drains []string
Hostname string
}
NextID int `json:"next_id"`
}