-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
45 lines (37 loc) · 957 Bytes
/
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
package jsonrpc2
import (
"bytes"
"context"
"io/ioutil"
"net/http"
)
type (
// HTTPClient is a convenient interface for http worker.
// It allows to use a custom http transport level implementation.
HTTPClient interface {
Post(ctx context.Context, url string, body []byte) ([]byte, error)
}
httpClient struct {
c *http.Client
}
)
// Post makes http request with method POST to url with body.
func (h *httpClient) Post(ctx context.Context, url string, body []byte) ([]byte, error) {
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentTypeApplicationJSON)
resp, err := h.c.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// NewHttpClient returns wiring of standard http.Client.
func NewHttpClient(c *http.Client) HTTPClient {
return &httpClient{
c: c,
}
}