-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathrequest.go
69 lines (57 loc) · 1.43 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
package pushover
import (
"encoding/json"
"net/http"
"net/url"
"strings"
)
// do is a generic function to send a request to the API.
func do(req *http.Request, resType interface{}, returnHeaders bool) error {
client := http.DefaultClient
// Send request
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Only 500 errors will not respond a readable result
if resp.StatusCode >= http.StatusInternalServerError {
return ErrHTTPPushover
}
// Decode the JSON response
if err := json.NewDecoder(resp.Body).Decode(&resType); err != nil {
return err
}
// Check if the unmarshaled data is a response
r, ok := resType.(*Response)
if !ok {
return nil
}
// Check response status
if r.Status != 1 {
return r.Errors
}
// The headers are only returned when posting a new notification
if returnHeaders {
// Get app limits from headers
appLimits, err := newLimit(resp.Header)
if err != nil {
return err
}
r.Limit = appLimits
}
return nil
}
// urlEncodedRequest returns a new url encoded request.
func newURLEncodedRequest(method, endpoint string, params map[string]string) (*http.Request, error) {
urlValues := url.Values{}
for k, v := range params {
urlValues.Add(k, v)
}
req, err := http.NewRequest(method, endpoint, strings.NewReader(urlValues.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req, nil
}