/
client.go
67 lines (55 loc) · 1.53 KB
/
client.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
// Simple client for submitting commands over HTTP
package httpcommandclient
import (
"context"
"fmt"
"net/http"
"github.com/function61/eventkit/command"
"github.com/function61/eventkit/httpcommand"
"github.com/function61/gokit/net/http/ezhttp"
)
type Client struct {
baseUrl string // looks like "http://localhost/command/"
bearerToken string
httpClient *http.Client
}
func New(baseUrl string, bearerToken string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
baseUrl: baseUrl,
bearerToken: bearerToken,
httpClient: httpClient,
}
}
func (c *Client) Exec(ctx context.Context, cmdStruct command.Command) error {
_, err := c.execInternal(ctx, cmdStruct)
return err
}
func (c *Client) ExecExpectingCreatedRecordId(ctx context.Context, cmdStruct command.Command) (string, error) {
res, err := c.execInternal(ctx, cmdStruct)
if err != nil {
return "", err
}
collectionId := res.Header.Get(httpcommand.CreatedRecordIdHeaderKey)
if collectionId == "" {
return "", fmt.Errorf("didn't get back a %s header", httpcommand.CreatedRecordIdHeaderKey)
}
return collectionId, nil
}
func (c *Client) execInternal(ctx context.Context, cmdStruct command.Command) (*http.Response, error) {
if err := cmdStruct.Validate(); err != nil {
return nil, err
}
res, err := ezhttp.Post(
ctx,
c.baseUrl+cmdStruct.Key(),
ezhttp.AuthBearer(c.bearerToken),
ezhttp.SendJson(cmdStruct),
ezhttp.Client(c.httpClient))
if err != nil {
return nil, err
}
return res, nil
}