From 9446886b37dc0614d7847a452e39f7f88f03f0d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20K=C3=A4mmerling?= Date: Sat, 20 Mar 2021 05:43:54 +0100 Subject: [PATCH] Fix HackerNews Widget (#1063) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After commit 49109c77f719cedc5c7f15bcf255f952d2c3b90d the HackerNews widget did not work as expected. It failed with a error message "http: read on closed response body". This commit fixes the underlying reader issue by reading the whole request body within the apiRequest function and returning the []bytes of the response instead of *http.Response. If we want to continue to return *http.Response this would lead to the problem that the caller (GetStory() and GetStories()) always need to close the Request Body. The ways before this MR is a bit problematic because the defer gets executed when the function is "done", so it closes the Body already before the utils.ParseJSON can read it. Signed-off-by: Lukas Kämmerling --- modules/hackernews/client.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/modules/hackernews/client.go b/modules/hackernews/client.go index 91034e83..6cf4af99 100644 --- a/modules/hackernews/client.go +++ b/modules/hackernews/client.go @@ -1,7 +1,9 @@ package hackernews import ( + "bytes" "fmt" + "io/ioutil" "net/http" "strconv" "strings" @@ -19,7 +21,7 @@ func GetStories(storyType string) ([]int, error) { return storyIds, err } - err = utils.ParseJSON(&storyIds, resp.Body) + err = utils.ParseJSON(&storyIds, bytes.NewReader(resp)) if err != nil { return storyIds, err } @@ -36,7 +38,7 @@ func GetStory(id int) (Story, error) { return story, err } - err = utils.ParseJSON(&story, resp.Body) + err = utils.ParseJSON(&story, bytes.NewReader(resp)) if err != nil { return story, err } @@ -50,7 +52,7 @@ var ( apiEndpoint = "https://hacker-news.firebaseio.com/v0/" ) -func apiRequest(path string) (*http.Response, error) { +func apiRequest(path string) ([]byte, error) { req, err := http.NewRequest("GET", apiEndpoint+path+".json", nil) if err != nil { return nil, err @@ -61,11 +63,16 @@ func apiRequest(path string) (*http.Response, error) { if err != nil { return nil, err } + defer func() { _ = resp.Body.Close() }() if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf(resp.Status) } - return resp, nil + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return body, nil }