From 765a887d9cd53b76fae22516266a5f4e80aca250 Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Tue, 30 Jul 2019 13:22:09 +0200 Subject: [PATCH] io.EOF workaround --- http.go | 7 ------- json.go | 23 +++++++++++++++++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/http.go b/http.go index 7e04a44..a2fc796 100644 --- a/http.go +++ b/http.go @@ -3,7 +3,6 @@ package webutility import ( "encoding/json" "fmt" - "io" "net/http" ) @@ -150,9 +149,3 @@ func Conflict(w http.ResponseWriter, r *http.Request, err string) { func InternalServerError(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusInternalServerError, err) } - -// DecodeJSON decodes JSON data from r to v. -// Returns an error if it fails. -func DecodeJSON(r io.Reader, v interface{}) error { - return json.NewDecoder(r).Decode(v) -} diff --git a/json.go b/json.go index 4e51ab1..690c62b 100644 --- a/json.go +++ b/json.go @@ -1,12 +1,21 @@ package webutility +// TODO(marko): If DecodeJSON() returns io.EOF treat it as if there is no response body, since response content length can sometimes be -1. + import ( "bytes" "encoding/json" + "io" "net/http" "net/url" ) +// DecodeJSON decodes JSON data from r to v. +// Returns an error if it fails. +func DecodeJSON(r io.Reader, v interface{}) error { + return json.NewDecoder(r).Decode(v) +} + func GetJSON(url string, v interface{}, params url.Values, headers http.Header) (status int, err error) { p := params.Encode() if p != "" { @@ -34,9 +43,14 @@ func GetJSON(url string, v interface{}, params url.Values, headers http.Header) if err != nil { return 0, err } + defer resp.Body.Close() status = resp.StatusCode - return status, DecodeJSON(resp.Body, v) + if err = DecodeJSON(resp.Body, v); err == io.EOF { + err = nil + } + + return status, err } 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 return 0, err } status = resp.StatusCode + defer resp.Body.Close() + + if err = DecodeJSON(resp.Body, v); err == io.EOF { + err = nil + } - return status, DecodeJSON(resp.Body, r) + return status, err } -- 1.8.1.2