-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathkeys.go
106 lines (80 loc) · 2 KB
/
keys.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
// keys.go
// This file implements the keys API calls
package atlas
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
)
type keyList struct {
Count int
Next string
Previous string
Results []Key
}
// fetch the given resource
func (c *Client) fetchOneKeyPage(opts map[string]string) (raw *keyList, err error) {
opts = c.addAPIKey(opts)
opts = mergeOptions(opts, c.opts)
req := c.prepareRequest("GET", "keys", opts)
resp, err := c.call(req)
if err != nil {
return nil, errors.Wrap(err, "fetchOneKeyPage/call")
}
body, err := c.handleAPIResponse(resp)
if err != nil {
return &keyList{}, errors.Wrap(err, "fetchOneKeyPage")
}
raw = &keyList{}
err = json.Unmarshal(body, raw)
return
}
// GetKey returns a given API key
func (c *Client) GetKey(uuid string) (k Key, err error) {
opts := make(map[string]string)
opts = c.addAPIKey(opts)
opts = mergeOptions(opts, c.opts)
req := c.prepareRequest("GET", fmt.Sprintf("keys/%s", uuid), opts)
//log.Printf("req: %#v", req)
resp, err := c.call(req)
if err != nil {
return Key{}, errors.Wrap(err, "GetKey/call")
}
body, err := c.handleAPIResponse(resp)
if err != nil {
return Key{}, errors.Wrap(err, "GetKey")
}
k = Key{}
err = json.Unmarshal(body, &k)
c.debug("json: %#v\n", k)
return
}
// GetKeys returns all your API keys
func (c *Client) GetKeys(opts map[string]string) (kl []Key, err error) {
opts = c.addAPIKey(opts)
opts = mergeOptions(opts, c.opts)
// First call
rawlist, err := c.fetchOneKeyPage(opts)
if err != nil {
return []Key{}, errors.Wrap(err, "GetKeys")
}
// Empty answer
if rawlist.Count == 0 {
return nil, fmt.Errorf("empty key list")
}
var res []Key
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.fetchOneKeyPage(opts)
if err != nil {
return
}
res = append(res, rawlist.Results...)
}
}
kl = res
return
}