-
Notifications
You must be signed in to change notification settings - Fork 7
/
response.go
56 lines (47 loc) · 1.09 KB
/
response.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
package hasaki
import (
"context"
"github.com/pkg/errors"
"io"
"net/http"
"net/url"
)
type Response struct {
*http.Response
ctx context.Context
err error
}
func (c *Response) Err() error {
return c.err
}
func (c *Response) Context() context.Context {
return c.ctx
}
func (c *Response) ReadBody() ([]byte, error) {
if c.err != nil {
return nil, c.err
}
if c.Response == nil || c.Body == nil {
return nil, errors.WithStack(errEmptyResponse)
}
if v, ok := c.Body.(BytesReadCloser); ok {
return v.Bytes(), nil
}
b, err := io.ReadAll(c.Body)
_ = c.Body.Close()
return b, errors.WithStack(err)
}
func (c *Response) BindJSON(v any) error { return c.Bind(v, JsonCodec) }
func (c *Response) BindXML(v any) error { return c.Bind(v, XmlCodec) }
func (c *Response) BindForm(v *url.Values) error { return c.Bind(v, FormCodec) }
func (c *Response) Bind(v any, decoder Decoder) error {
if c.err != nil {
return c.err
}
if c.Response == nil || c.Body == nil {
return errors.WithStack(errEmptyResponse)
}
err := decoder.Decode(c.Body, v)
_ = c.Body.Close()
return errors.WithStack(err)
}