-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathserver.go
More file actions
97 lines (85 loc) · 2.04 KB
/
Copy pathserver.go
File metadata and controls
97 lines (85 loc) · 2.04 KB
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
package honeybadger
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
// Errors returned by the backend when unable to successfully handle payload.
var (
ErrRateExceeded = errors.New("Rate exceeded: slow down!")
ErrPaymentRequired = errors.New("Payment required: expired trial or credit card?")
ErrUnauthorized = errors.New("Unauthorized: bad API key?")
)
func newServerBackend(config *Configuration) *server {
return &server{
URL: &config.Endpoint,
APIKey: &config.APIKey,
Client: &http.Client{
Transport: http.DefaultTransport,
Timeout: config.Timeout,
},
Timeout: &config.Timeout,
}
}
type server struct {
APIKey *string
URL *string
Timeout *time.Duration
Client *http.Client
}
func (s *server) Notify(feature Feature, payload Payload) error {
return s.sendRequest("v1/"+feature.Endpoint, payload.toJSON(), "application/json")
}
func (s *server) Event(events []*eventPayload) error {
var jsonl []byte
for _, event := range events {
jsonl = append(jsonl, event.toJSON()...)
jsonl = append(jsonl, '\n')
}
return s.sendRequest("v1/events", jsonl, "application/x-ndjson")
}
func (s *server) sendRequest(path string, body []byte, contentType string) error {
s.Client.Timeout = *s.Timeout
url, err := url.Parse(*s.URL)
if err != nil {
return err
}
url.Path = path
req, err := http.NewRequest("POST", url.String(), bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("X-API-Key", *s.APIKey)
req.Header.Set("Content-Type", contentType)
req.Header.Set("Accept", "application/json")
resp, err := s.Client.Do(req)
if err != nil {
return err
}
defer func() {
io.ReadAll(resp.Body)
resp.Body.Close()
}()
switch resp.StatusCode {
case 200, 201:
return nil
case 429, 503:
return ErrRateExceeded
case 402:
return ErrPaymentRequired
case 403:
return ErrUnauthorized
default:
bodyBytes, _ := io.ReadAll(resp.Body)
return fmt.Errorf(
"request failed status=%d expected=%d message=%q",
resp.StatusCode,
http.StatusCreated,
string(bodyBytes),
)
}
}