-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
83 lines (74 loc) · 2.01 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package gaurun
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"runtime"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
const version = "1.0"
var userAgent = fmt.Sprintf("GaurunGoClient/%s (%s)", version, runtime.Version())
// A Client for gaurun server.
type Client struct {
Endpoint *url.URL
HTTPClient *http.Client
}
// NewClient generates a client for gaurun server.
func NewClient(endpoint string, cli *http.Client) (*Client, error) {
u, err := url.ParseRequestURI(endpoint)
if err != nil {
return nil, errors.Wrapf(err, "gaurun: failed to parse url - endpoint = %s", endpoint)
}
if cli == nil {
cli = http.DefaultClient
}
return &Client{
Endpoint: u,
HTTPClient: cli,
}, nil
}
// PushMulti sends payloads to gaurun server.
func (cli *Client) PushMulti(c context.Context, ps ...*Payload) error {
eg, ctx := errgroup.WithContext(c)
for _, p := range ps {
eg.Go(func() error {
return cli.Push(ctx, p)
})
}
if err := eg.Wait(); err != nil {
return err
}
return nil
}
// Push sends a payload to gaurun server.
func (cli *Client) Push(c context.Context, p *Payload) error {
return cli.do(http.MethodPost, "/push", p)
}
func (cli *Client) do(method, spath string, body interface{}) error {
bin, err := json.Marshal(body)
if err != nil {
return errors.Wrapf(err, "gaurun: failed to marshal json - body = %+v", body)
}
u := *cli.Endpoint
u.Path = path.Join(cli.Endpoint.Path, spath)
req, err := http.NewRequest(method, u.String(), bytes.NewReader(bin))
if err != nil {
return errors.Wrapf(err, "gaurun: failed to generate new http request - method = %s, path = %s, body = %+v", method, spath, body)
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Content-type", "application/json")
resp, err := cli.HTTPClient.Do(req)
if err != nil {
return errors.Wrapf(err, "gaurun: failed to send http request - request = %+v", req)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
return NewError(resp)
}