/
response.go
71 lines (55 loc) · 1.1 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
package HttpRequest
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
)
type Response struct {
time int64
url string
resp *http.Response
}
func (r *Response) Response() *http.Response {
return r.resp
}
func (r *Response) StatusCode() int {
if r.resp == nil {
return 0
}
return r.resp.StatusCode
}
func (r *Response) Time() string {
return strconv.Itoa(int(r.time)) + "ms"
}
func (r *Response) Url() string {
return r.url
}
func (r *Response) Body() ([]byte, error) {
defer r.resp.Body.Close()
if r.resp == nil || r.resp.Body == nil {
return nil, errors.New("response or body is nil")
}
b, err := ioutil.ReadAll(r.resp.Body)
if err != nil {
return nil, err
}
return b, nil
}
func (r *Response) Json() (string, error) {
defer r.resp.Body.Close()
if r.resp == nil || r.resp.Body == nil {
return "", errors.New("response or body is nil")
}
b, err := ioutil.ReadAll(r.resp.Body)
if err != nil {
return "", err
}
var i interface{}
err = json.Unmarshal(b, &i)
if err != nil {
return "", errors.New("Illegal json: "+err.Error())
}
return Json(i), nil
}