forked from PagerDuty/go-pagerduty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
90 lines (78 loc) · 2.27 KB
/
client.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
package pagerduty
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
log "github.com/Sirupsen/logrus"
)
// APIObject represents generic api json response that is shared by most
// domain object (like escalation
type APIObject struct {
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Summary string `json:"summary,omitempty"`
Self string `json:"self,omitempty"`
HtmlUrl string `json:"html_url,omitempty"`
}
type APIListObject struct {
Limit uint `url:"limit,omitempty"`
Offset uint `url:"offset,omitempty"`
More bool `url:"more,omitempty"`
Total uint `url:"total,omitempty"`
}
// Client wraps http client
type Client struct {
Subdomain string
authToken string
}
// NewClient creates an API client
func NewClient(subdomain, authToken string) *Client {
return &Client{
Subdomain: subdomain,
authToken: authToken,
}
}
func (c *Client) Delete(path string) (*http.Response, error) {
return c.Do("DELETE", path, nil)
}
func (c *Client) Put(path string, payload interface{}) (*http.Response, error) {
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
return c.Do("PUT", path, bytes.NewBuffer(data))
}
func (c *Client) Post(path string, payload interface{}) (*http.Response, error) {
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
log.Debugln(string(data))
return c.Do("POST", path, bytes.NewBuffer(data))
}
func (c *Client) Get(path string) (*http.Response, error) {
return c.Do("GET", path, nil)
}
func (c *Client) Do(method, path string, body io.Reader) (*http.Response, error) {
endpoint := "https://" + c.Subdomain + ".pagerduty.com/api/v1" + path
log.Debugln("Endpoint:", endpoint)
req, _ := http.NewRequest(method, endpoint, body)
req.Header.Set("Accept", "application/vnd.pagerduty+json;version=2")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Token token="+c.authToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return resp, fmt.Errorf("HTTP Status Code: %d", resp.StatusCode)
}
return resp, nil
}
func (c *Client) decodeJson(resp *http.Response, payload interface{}) error {
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
return decoder.Decode(payload)
}