mirror of
https://github.com/taigrr/wtf
synced 2025-01-18 04:03:14 -08:00
Fix JSON parsing
Issue #600 points out Jenkins module panics occasionally I noticed that a number of places panic because of JSON parsing Centralize JSON parsing, have it return an error, and have widgets report the error
This commit is contained in:
@@ -1,14 +1,12 @@
|
||||
package hackernews
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/wtfutil/wtf/utils"
|
||||
)
|
||||
|
||||
func GetStories(storyType string) ([]int, error) {
|
||||
@@ -21,7 +19,10 @@ func GetStories(storyType string) ([]int, error) {
|
||||
return storyIds, err
|
||||
}
|
||||
|
||||
parseJson(&storyIds, resp.Body)
|
||||
err = utils.ParseJson(&storyIds, resp.Body)
|
||||
if err != nil {
|
||||
return storyIds, err
|
||||
}
|
||||
}
|
||||
|
||||
return storyIds, nil
|
||||
@@ -35,7 +36,10 @@ func GetStory(id int) (Story, error) {
|
||||
return story, err
|
||||
}
|
||||
|
||||
parseJson(&story, resp.Body)
|
||||
err = utils.ParseJson(&story, resp.Body)
|
||||
if err != nil {
|
||||
return story, err
|
||||
}
|
||||
|
||||
return story, nil
|
||||
}
|
||||
@@ -61,20 +65,3 @@ func apiRequest(path string) (*http.Response, error) {
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func parseJson(obj interface{}, text io.Reader) {
|
||||
jsonStream, err := ioutil.ReadAll(text)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(jsonStream))
|
||||
|
||||
for {
|
||||
if err := decoder.Decode(obj); err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user