-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.go
197 lines (165 loc) · 4 KB
/
request.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package jamf
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
"github.com/cenkalti/backoff"
)
const (
duplicateNameErr string = "Duplicate Name"
)
type Error interface {
Error() string
StatusCode() int
URI() string
Body() string
}
type errorInfo struct {
statusCode int
uri string
body string
}
func newError(statusCode int, uri, body string) Error {
var e = new(errorInfo)
e.statusCode = statusCode
e.uri = uri
e.body = body
return e
}
func (e *errorInfo) Error() string {
return fmt.Sprintf("API Error: %v URI: %s Body: %s", e.statusCode, e.uri, e.body)
}
func (e *errorInfo) StatusCode() int {
return e.statusCode
}
func (e *errorInfo) URI() string {
return e.uri
}
func (e *errorInfo) Body() string {
return e.body
}
// doJsonRequest ... A method to send a request to the jamf api
func (c *Client) doRequest(method, api string, reqbody, out interface{}) error {
req, err := c.createRequest(method, api, reqbody)
if err != nil {
return err
}
// request
var resp *http.Response
if method == "POST" || method == "PUT" {
resp, err = c.HttpClient.Do(req)
} else {
resp, err = c.doRequestWithRetries(req)
}
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
re := regexp.MustCompile(`\r?\n`)
out := re.ReplaceAllString(string(body), " ")
return newError(resp.StatusCode, api, out)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
// If we got no body, by default let's just make an empty JSON dict.
if len(body) == 0 {
body = []byte{'{', '}'}
}
if strings.Contains(api, "JSSResource") {
err = xml.Unmarshal(body, out)
} else {
err = json.Unmarshal(body, out)
}
return err
}
// doRequestWithRetries ... GET/DELETE depends on the jamf server, the retry process is largely
// Use backoff to extend the wait interval for retrying exponentially.
func (c *Client) doRequestWithRetries(req *http.Request) (*http.Response, error) {
var (
err error
resp *http.Response
bo = backoff.NewExponentialBackOff()
body []byte
)
bo.MaxElapsedTime = c.HttpRetryTimeout
if req.Body != nil {
body, err = ioutil.ReadAll(req.Body)
if err != nil {
return resp, err
}
}
boReq := func() error {
if body != nil {
req.Body = ioutil.NopCloser(bytes.NewReader(body))
}
resp, err = c.HttpClient.Do(req)
if err != nil {
return err
}
// 2xx are done. 4xx are not retry
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil
}
return fmt.Errorf("received http status code %d", resp.StatusCode)
}
err = backoff.Retry(boReq, bo)
return resp, err
}
// uriForApi ... Generate uri for api
func (c *Client) uriForAPI(api string) string {
return fmt.Sprintf("https://%s%s", c.url, api)
}
// createRequest ... Generate a http request for api.
func (c *Client) createRequest(method, api string, reqbody interface{}) (*http.Request, error) {
var bodyReader io.Reader
// Convert the request body to the appropriate type
if method != "GET" && reqbody != nil {
if strings.Contains(api, "JSSResource") {
b, err := xml.Marshal(reqbody)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(b)
} else {
b, err := json.Marshal(reqbody)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(b)
}
}
req, err := http.NewRequest(method, c.uriForAPI(api), bodyReader)
if err != nil {
return nil, err
}
// Set the necessary headers
if strings.Contains(api, "JSSResource") || c.token == nil {
req.Header.Add("Content-Type", "application/xml")
req.SetBasicAuth(c.username, c.password)
} else {
req.Header.Add("Content-Type", "application/json")
if c.token != nil {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", *c.token))
}
}
for k, v := range c.ExtraHeader {
req.Header.Add(k, v)
}
return req, err
}