-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdestination_http.go
51 lines (45 loc) · 1 KB
/
destination_http.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
package opinionatedevents
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type httpDestination struct {
endpoint string
client httpClient
}
func NewHTTPDestination(endpoint string) *httpDestination {
return &httpDestination{
endpoint: endpoint,
client: http.DefaultClient,
}
}
func (d *httpDestination) setClient(client httpClient) {
d.client = client
}
func (d *httpDestination) Deliver(_ context.Context, batch []*Message) error {
payload, err := json.Marshal(batch)
if err != nil {
return err
}
// construct the request
req, err := http.NewRequest(http.MethodPost, d.endpoint, bytes.NewBuffer(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// make the request
resp, err := d.client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("endpoint returned a non-200 status code: %d", resp.StatusCode)
}
return nil
}