-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.go
65 lines (54 loc) · 1.35 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package usage
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type Client struct {
HTTPClient
SessionEndpoint string
ReportEndpoint string
}
func (c *Client) NewSession(ctx context.Context, in *SessionRequest) (*SessionReply, error) {
reply := &SessionReply{}
err := c.Send(ctx, c.SessionEndpoint, in, reply)
return reply, err
}
func (c *Client) SendReport(ctx context.Context, in *ReportRequest) (*ReportReply, error) {
reply := &ReportReply{}
err := c.Send(ctx, c.ReportEndpoint, in, reply)
return reply, err
}
type HTTPClient interface {
Send(context.Context, string, interface{}, interface{}) error
}
type BasicClient struct {
Client *http.Client
URL string
UserAgent string
}
func (c *BasicClient) Send(ctx context.Context, path string, in, out interface{}) error {
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(in); err != nil {
return err
}
req, err := http.NewRequest("POST", c.URL+path, buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
resp, err := c.Client.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(out)
}