Commit 8c6dd0499554f1acdb7b2f389880291dac4dee9d
1 parent
d76a611ee8
Exists in
master
GetContent
Showing
2 changed files
with
55 additions
and
6 deletions
Show diff stats
file_util.go
json.go
... | ... | @@ -6,10 +6,52 @@ import ( |
6 | 6 | "bytes" |
7 | 7 | "encoding/json" |
8 | 8 | "io" |
9 | + "io/ioutil" | |
9 | 10 | "net/http" |
10 | 11 | "net/url" |
11 | 12 | ) |
12 | 13 | |
14 | +func GetContent(url string, params url.Values, headers http.Header) (content []byte, status int, err error) { | |
15 | + if params != nil { | |
16 | + p := params.Encode() | |
17 | + if p != "" { | |
18 | + url += "?" + p | |
19 | + } | |
20 | + } | |
21 | + | |
22 | + req, err := http.NewRequest(http.MethodGet, url, nil) | |
23 | + if err != nil { | |
24 | + return nil, 0, err | |
25 | + } | |
26 | + | |
27 | + if headers != nil { | |
28 | + for k, head := range headers { | |
29 | + for i, h := range head { | |
30 | + if i == 0 { | |
31 | + req.Header.Set(k, h) | |
32 | + } else { | |
33 | + req.Header.Add(k, h) | |
34 | + } | |
35 | + } | |
36 | + } | |
37 | + } | |
38 | + | |
39 | + resp, err := http.DefaultClient.Do(req) | |
40 | + if err != nil { | |
41 | + return nil, 0, err | |
42 | + } | |
43 | + defer resp.Body.Close() | |
44 | + status = resp.StatusCode | |
45 | + | |
46 | + if status != http.StatusOK { | |
47 | + return nil, status, err | |
48 | + } | |
49 | + | |
50 | + content, err = ioutil.ReadAll(resp.Body) | |
51 | + | |
52 | + return content, status, err | |
53 | +} | |
54 | + | |
13 | 55 | // DecodeJSON decodes JSON data from r to v. |
14 | 56 | // Returns an error if it fails. |
15 | 57 | func DecodeJSON(r io.Reader, v interface{}) error { |
... | ... | @@ -17,9 +59,11 @@ func DecodeJSON(r io.Reader, v interface{}) error { |
17 | 59 | } |
18 | 60 | |
19 | 61 | func GetJSON(url string, v interface{}, params url.Values, headers http.Header) (status int, err error) { |
20 | - p := params.Encode() | |
21 | - if p != "" { | |
22 | - url += "?" + p | |
62 | + if params != nil { | |
63 | + p := params.Encode() | |
64 | + if p != "" { | |
65 | + url += "?" + p | |
66 | + } | |
23 | 67 | } |
24 | 68 | |
25 | 69 | req, err := http.NewRequest(http.MethodGet, url, nil) |
... | ... | @@ -61,9 +105,11 @@ func PostJSON(url string, v, r interface{}, params url.Values, headers http.Head |
61 | 105 | buffer := bytes.NewBuffer(make([]byte, 0)) |
62 | 106 | json.NewEncoder(buffer).Encode(v) |
63 | 107 | |
64 | - p := params.Encode() | |
65 | - if p != "" { | |
66 | - url += "?" + p | |
108 | + if params != nil { | |
109 | + p := params.Encode() | |
110 | + if p != "" { | |
111 | + url += "?" + p | |
112 | + } | |
67 | 113 | } |
68 | 114 | |
69 | 115 | req, err := http.NewRequest(http.MethodPost, url, buffer) | ... | ... |