-
Notifications
You must be signed in to change notification settings - Fork 0
/
heartbeat.go
76 lines (65 loc) · 1.72 KB
/
heartbeat.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
package heartbeat
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/sethgrid/pester"
)
const defaultEndpoint = "https://api.opsgenie.com"
var (
// ErrUnauthorised signafies an invalid api key
ErrUnauthorised = errors.New("invalid api key")
// ErrNonOkStatusCode a non 2XX status code was returned
ErrNonOkStatusCode = errors.New("non 200 status code")
)
// PingRequest handles talking to the Opsgenie Heartbeat API
type PingRequest struct {
// APIKey used to talk to the API
APIKey string
Endpoint string
Client HTTPClient
}
// HTTPClient represents an HTTP client that can make a request
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
// New creates a PingRequest with a default HTTP client and API key from env variable
func New(key string) PingRequest {
client := pester.New()
client.Timeout = 10 * time.Second
client.Concurrency = 3
client.MaxRetries = 5
client.Backoff = pester.ExponentialJitterBackoff
return PingRequest{
APIKey: key,
Endpoint: defaultEndpoint,
Client: client,
}
}
// Ping performs a HTTP request to the Opsgenie Heartbeat Ping endpoint
func (r PingRequest) Ping(ctx context.Context, heartbeat string) error {
url := fmt.Sprintf("%s/v2/heartbeats/%s/ping", strings.TrimRight(r.Endpoint, "/"), heartbeat)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "GenieKey "+r.APIKey)
req.WithContext(ctx)
resp, err := r.Client.Do(req)
if err != nil {
return err
}
if resp.Body != nil {
defer resp.Body.Close()
}
if resp.StatusCode == http.StatusUnauthorized {
return ErrUnauthorised
}
if c := resp.StatusCode; c < 200 || c > 299 {
return ErrNonOkStatusCode
}
return nil
}