-
Notifications
You must be signed in to change notification settings - Fork 6
/
probes.go
118 lines (92 loc) · 2.43 KB
/
probes.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// probes.go
//
// This file implements the probe API calls
package atlas
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
)
// GetProbe returns data for a single probe
func (c *Client) GetProbe(id int) (p *Probe, err error) {
opts := make(map[string]string)
opts = c.addAPIKey(opts)
opts = mergeOptions(opts, c.opts)
c.debug("opts=%v", opts)
req := c.prepareRequest("GET", fmt.Sprintf("probes/%d", id), opts)
c.debug("req=%#v", req)
resp, err := c.call(req)
c.debug("resp=%#v", resp)
if err != nil {
c.verbose("call: %v", err)
return &Probe{}, errors.Wrap(err, "GetProbe")
}
body, err := c.handleAPIResponse(resp)
if err != nil {
return &Probe{}, errors.Wrap(err, "GetProbe")
}
p = &Probe{}
err = json.Unmarshal(body, p)
c.debug("p=%#v", p)
return
}
// probeList is our main answer
type probeList struct {
Count int
Next string
Previous string
Results []Probe
}
// fetch the given resource
func (c *Client) fetchOneProbePage(opts map[string]string) (raw *probeList, err error) {
opts = mergeOptions(opts, c.opts)
opts = c.addAPIKey(opts)
c.debug("opts=%v", opts)
req := c.prepareRequest("GET", "probes", opts)
resp, err := c.call(req)
if err != nil {
return &probeList{}, errors.Wrap(err, "fetchOneProbePage/call")
}
// We may have all http errors here but the request did succeed
c.debug("http.code=%d", resp.StatusCode)
body, err := c.handleAPIResponse(resp)
if err != nil {
return &probeList{}, errors.Wrap(err, "GetProbes")
}
raw = &probeList{}
err = json.Unmarshal(body, raw)
if err != nil {
c.log.Printf("err reading json: raw=%#v err=%v", raw, err)
return raw, errors.Wrapf(err, "fetchOneProbePage")
}
c.verbose("Count=%d raw=%v", raw.Count, resp)
c.debug("P")
return
}
// GetProbes returns data for a collection of probes
func (c *Client) GetProbes(opts map[string]string) (p []Probe, err error) {
// First call
rawlist, err := c.fetchOneProbePage(opts)
if err != nil {
return []Probe{}, errors.Wrap(err, "GetProbes")
}
// Empty answer
if rawlist.Count == 0 {
return nil, fmt.Errorf("empty probe list")
}
var res []Probe
res = append(res, rawlist.Results...)
if rawlist.Next != "" {
// We have pagination
for pn := getPageNum(rawlist.Next); rawlist.Next != ""; pn = getPageNum(rawlist.Next) {
opts["page"] = pn
rawlist, err = c.fetchOneProbePage(opts)
if err != nil {
return
}
res = append(res, rawlist.Results...)
}
}
p = res
return
}