/
client.go
72 lines (56 loc) · 1.17 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
package http
import (
"io/ioutil"
native "net/http"
"strings"
"github.com/kevinanthony/bzen/http/encoder"
"github.com/pkg/errors"
)
var (
errBadRequest = errors.New("bad request")
)
type Client interface {
Do(req *native.Request, v interface{}) error
}
type Native interface {
Do(req *native.Request) (*native.Response, error)
}
type client struct {
encFactory encoder.Factory
client Native
}
func NewClient(nativeClient Native, enc encoder.Factory) Client {
if nativeClient == nil {
panic("http client is required")
}
if enc == nil {
panic("encoding factory is required")
}
return &client{
encFactory: enc,
client: nativeClient,
}
}
func (c client) Do(req *native.Request, v interface{}) error {
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer func() {
if resp.Body != nil {
_ = resp.Body.Close()
}
}()
bts, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode >= native.StatusBadRequest {
return errors.Wrapf(errBadRequest, "%d: %s",
resp.StatusCode, strings.Trim(string(bts), "\""))
}
if len(bts) == 0 {
return nil
}
return c.encFactory.Create(resp).Decode(bts, v)
}