1
0
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:
Sean Smith
2019-09-07 15:10:37 -04:00
parent 32884e5de4
commit 36fbad54d8
8 changed files with 73 additions and 162 deletions

View File

@@ -1,13 +1,11 @@
package gitter
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"github.com/wtfutil/wtf/utils"
)
func GetMessages(roomId string, numberOfMessages int, apiToken string) ([]Message, error) {
@@ -18,7 +16,10 @@ func GetMessages(roomId string, numberOfMessages int, apiToken string) ([]Messag
return nil, err
}
parseJson(&messages, resp.Body)
err = utils.ParseJson(&messages, resp.Body)
if err != nil {
return nil, err
}
return messages, nil
}
@@ -31,7 +32,10 @@ func GetRoom(roomUri, apiToken string) (*Room, error) {
return nil, err
}
parseJson(&rooms, resp.Body)
err = utils.ParseJson(&rooms, resp.Body)
if err != nil {
return nil, err
}
for _, room := range rooms.Results {
if room.URI == roomUri {
@@ -65,20 +69,3 @@ func apiRequest(path, apiToken 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)
}
}
}