forked from PagerDuty/go-pagerduty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
63 lines (57 loc) · 2.17 KB
/
event.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
package pagerduty
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
const eventEndPoint = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
// Event stores data for problem reporting, acknowledgement, and resolution.
type Event struct {
ServiceKey string `json:"service_key"`
Type string `json:"event_type"`
IncidentKey string `json:"incident_key,omitempty"`
Description string `json:"description"`
Client string `json:"client,omitempty"`
ClientURL string `json:"client_url,omitempty"`
Details interface{} `json:"details,omitempty"`
Contexts []interface{} `json:"contexts,omitempty"`
}
// EventResponse is the data returned from the CreateEvent API endpoint.
type EventResponse struct {
Status string `json:"status"`
Message string `json:"message"`
IncidentKey string `json:"incident_key"`
HttpStatus int
}
// CreateEvent sends PagerDuty an event to trigger, acknowledge, or resolve a
// problem. If you need to provide a custom HTTP client, please use
// CreateEventWithHTTPClient.
func CreateEvent(e Event) (*EventResponse, error) {
return CreateEventWithHTTPClient(e, defaultHTTPClient)
}
// CreateEventWithHTTPClient sends PagerDuty an event to trigger, acknowledge,
// or resolve a problem. This function accepts a custom HTTP Client, if the
// default one used by this package doesn't fit your needs. If you don't need a
// custom HTTP client, please use CreateEvent instead.
func CreateEventWithHTTPClient(e Event, client HTTPClient) (*EventResponse, error) {
data, err := json.Marshal(e)
if err != nil {
return nil, err
}
req, _ := http.NewRequest("POST", eventEndPoint, bytes.NewBuffer(data))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return &EventResponse{HttpStatus: resp.StatusCode}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return &EventResponse{HttpStatus: resp.StatusCode}, fmt.Errorf("HTTP Status Code: %d", resp.StatusCode)
}
var eventResponse EventResponse
if err := json.NewDecoder(resp.Body).Decode(&eventResponse); err != nil {
return nil, err
}
return &eventResponse, nil
}