Commit 765a887d9cd53b76fae22516266a5f4e80aca250
1 parent
8a81bda58b
Exists in
master
io.EOF workaround
Showing
2 changed files
with
21 additions
and
9 deletions
Show diff stats
http.go
... | ... | @@ -3,7 +3,6 @@ package webutility |
3 | 3 | import ( |
4 | 4 | "encoding/json" |
5 | 5 | "fmt" |
6 | - "io" | |
7 | 6 | "net/http" |
8 | 7 | ) |
9 | 8 | |
... | ... | @@ -150,9 +149,3 @@ func Conflict(w http.ResponseWriter, r *http.Request, err string) { |
150 | 149 | func InternalServerError(w http.ResponseWriter, r *http.Request, err string) { |
151 | 150 | Error(w, r, http.StatusInternalServerError, err) |
152 | 151 | } |
153 | - | |
154 | -// DecodeJSON decodes JSON data from r to v. | |
155 | -// Returns an error if it fails. | |
156 | -func DecodeJSON(r io.Reader, v interface{}) error { | |
157 | - return json.NewDecoder(r).Decode(v) | |
158 | -} | ... | ... |
json.go
1 | 1 | package webutility |
2 | 2 | |
3 | +// TODO(marko): If DecodeJSON() returns io.EOF treat it as if there is no response body, since response content length can sometimes be -1. | |
4 | + | |
3 | 5 | import ( |
4 | 6 | "bytes" |
5 | 7 | "encoding/json" |
8 | + "io" | |
6 | 9 | "net/http" |
7 | 10 | "net/url" |
8 | 11 | ) |
9 | 12 | |
13 | +// DecodeJSON decodes JSON data from r to v. | |
14 | +// Returns an error if it fails. | |
15 | +func DecodeJSON(r io.Reader, v interface{}) error { | |
16 | + return json.NewDecoder(r).Decode(v) | |
17 | +} | |
18 | + | |
10 | 19 | func GetJSON(url string, v interface{}, params url.Values, headers http.Header) (status int, err error) { |
11 | 20 | p := params.Encode() |
12 | 21 | if p != "" { |
... | ... | @@ -34,9 +43,14 @@ func GetJSON(url string, v interface{}, params url.Values, headers http.Header) |
34 | 43 | if err != nil { |
35 | 44 | return 0, err |
36 | 45 | } |
46 | + defer resp.Body.Close() | |
37 | 47 | status = resp.StatusCode |
38 | 48 | |
39 | - return status, DecodeJSON(resp.Body, v) | |
49 | + if err = DecodeJSON(resp.Body, v); err == io.EOF { | |
50 | + err = nil | |
51 | + } | |
52 | + | |
53 | + return status, err | |
40 | 54 | } |
41 | 55 | |
42 | 56 | func PostJSON(url string, v, r interface{}, params url.Values, headers http.Header) (status int, err error) { |
... | ... | @@ -71,6 +85,11 @@ func PostJSON(url string, v, r interface{}, params url.Values, headers http.Head |
71 | 85 | return 0, err |
72 | 86 | } |
73 | 87 | status = resp.StatusCode |
88 | + defer resp.Body.Close() | |
89 | + | |
90 | + if err = DecodeJSON(resp.Body, v); err == io.EOF { | |
91 | + err = nil | |
92 | + } | |
74 | 93 | |
75 | - return status, DecodeJSON(resp.Body, r) | |
94 | + return status, err | |
76 | 95 | } | ... | ... |