-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.go
105 lines (81 loc) · 1.79 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package isuperagent
import (
"io/ioutil"
"net/http"
"github.com/charleslxh/isuperagent/bodyParser"
)
type Response interface {
IsOk() bool
GetHeaders() http.Header
GetBody() *Body
ParseBody(v interface{}) error
GetStatusCode() int
GetStatusText() string
GetHttpRequest() *http.Request
GetHttpResponse() *http.Response
}
type BodyInterface interface {
GetRaw() string
Unmarshal(v interface{}) error
}
type iresponse struct {
StatusCode int
StatusText string
Body *Body
Headers http.Header
HttpReq *http.Request
HttpResp *http.Response
}
type Body struct {
data []byte
contentType string
}
func (b *Body) GetData() []byte {
return b.data
}
func (b *Body) Unmarshal(v interface{}) error {
err := bodyParser.Unmarshal(b.contentType, b.data, v)
if err != nil {
return err
}
return nil
}
func NewResponse(req *http.Request, resp *http.Response) (Response, error) {
res := &iresponse{}
res.StatusCode = resp.StatusCode
res.StatusText = resp.Status
res.Headers = resp.Header
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
res.Body = &Body{data: content, contentType: resp.Header.Get("content-type")}
res.HttpReq = req
res.HttpResp = resp
return res, nil
}
func (r *iresponse) IsOk() bool {
return r.StatusCode == 200
}
func (r *iresponse) GetHeaders() http.Header {
return r.Headers
}
func (r *iresponse) GetBody() *Body {
return r.Body
}
func (r *iresponse) ParseBody(v interface{}) error {
return r.Body.Unmarshal(v)
}
func (r *iresponse) GetStatusCode() int {
return r.StatusCode
}
func (r *iresponse) GetStatusText() string {
return r.StatusText
}
func (r *iresponse) GetHttpRequest() *http.Request {
return r.HttpReq
}
func (r *iresponse) GetHttpResponse() *http.Response {
return r.HttpResp
}