forked from victorops/go-victorops
/
victorops.go
105 lines (88 loc) · 2.59 KB
/
victorops.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
package victorops
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"time"
)
// Client is the main client for interacting with victorops
type Client struct {
publicBaseURL string
apiID string
apiKey string
httpClient http.Client
}
// Client args is used to dynamically pass in parameters when instantiating the Client
type ClientArgs struct {
timeoutSeconds int
}
// RequestDetails contains details from the API response
type RequestDetails struct {
StatusCode int
ResponseBody string
RequestBody string
RawResponse *http.Response
RawRequest *http.Request
}
func (c Client) String() string {
return fmt.Sprintf("VictorOps Client: publicBaseURL: %s ", c.publicBaseURL)
}
func (c Client) makePublicAPICall(method string, endpoint string, requestBody io.Reader, queryParams map[string]string) (*RequestDetails, error) {
details := RequestDetails{}
// Create the request
req, err := http.NewRequest(method, c.publicBaseURL+"/api-public/"+endpoint, requestBody)
if err != nil {
return &details, err
}
// Set the auth headers needed for the public api
req.Header.Set("X-VO-Api-Id", c.apiID)
req.Header.Set("X-VO-Api-Key", c.apiKey)
req.Header.Set("Content-Type", "application/json")
// Set the query params
q := req.URL.Query()
for key, value := range queryParams {
q.Add(key, value)
}
req.URL.RawQuery = q.Encode()
// Add the request to the details
details.RawRequest = req
requestDump, err := httputil.DumpRequestOut(req, true)
if err != nil {
return &details, err
}
details.RequestBody = string(requestDump)
// Make the request
resp, err := c.httpClient.Do(req)
if err != nil {
return &details, err
}
// Read the entire response
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return &details, err
}
details.StatusCode = resp.StatusCode
details.ResponseBody = string(responseBody)
details.RawResponse = resp
return &details, nil
}
// NewClient creates a new VictorOps client
func NewClient(apiID string, apiKey string, publicBaseURL string) *Client {
return NewConfigurableClient(apiID, apiKey, publicBaseURL, http.Client{Timeout: time.Second * 30})
}
// NewConfigurableClient creates a new VictorOps client with ClientArgs struct
func NewConfigurableClient(apiID string, apiKey string, publicBaseURL string, httpClient http.Client) *Client {
client := Client{
apiID: apiID,
apiKey: apiKey,
publicBaseURL: publicBaseURL,
httpClient: httpClient,
}
return &client
}
// GetHTTPClient returns http client for the purpose of test
func (c Client) GetHTTPClient() *http.Client {
return &c.httpClient
}