-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathserver.go
82 lines (73 loc) · 1.68 KB
/
server.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
package honeybadger
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"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 {
// Copy the value from the pointer in case it has changed in the
// configuration.
s.Client.Timeout = *s.Timeout
url, err := url.Parse(*s.URL)
if err != nil {
return err
}
url.Path = "v1/" + feature.Endpoint
req, err := http.NewRequest("POST", url.String(), bytes.NewReader(payload.toJSON()))
if err != nil {
return err
}
req.Header.Set("X-API-Key", *s.APIKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := s.Client.Do(req)
if err != nil {
return err
}
defer func() {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}()
switch resp.StatusCode {
case 201:
return nil
case 429, 503:
return ErrRateExceeded
case 402:
return ErrPaymentRequired
case 403:
return ErrUnauthorized
default:
return fmt.Errorf(
"request failed status=%d expected=%d",
resp.StatusCode,
http.StatusCreated)
}
}