mirror of
https://github.com/taigrr/wtf
synced 2025-01-18 04:03:14 -08:00
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
72 lines
1.3 KiB
Go
72 lines
1.3 KiB
Go
package gitter
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/wtfutil/wtf/utils"
|
|
)
|
|
|
|
func GetMessages(roomId string, numberOfMessages int, apiToken string) ([]Message, error) {
|
|
var messages []Message
|
|
|
|
resp, err := apiRequest("rooms/"+roomId+"/chatMessages?limit="+strconv.Itoa(numberOfMessages), apiToken)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = utils.ParseJson(&messages, resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return messages, nil
|
|
}
|
|
|
|
func GetRoom(roomUri, apiToken string) (*Room, error) {
|
|
var rooms Rooms
|
|
|
|
resp, err := apiRequest("rooms?q="+roomUri, apiToken)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = utils.ParseJson(&rooms, resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for _, room := range rooms.Results {
|
|
if room.URI == roomUri {
|
|
return &room, nil
|
|
}
|
|
}
|
|
|
|
return nil, nil
|
|
}
|
|
|
|
/* -------------------- Unexported Functions -------------------- */
|
|
|
|
var (
|
|
apiBaseURL = "https://api.gitter.im/v1/"
|
|
)
|
|
|
|
func apiRequest(path, apiToken string) (*http.Response, error) {
|
|
req, err := http.NewRequest("GET", apiBaseURL+path, nil)
|
|
bearer := fmt.Sprintf("Bearer %s", apiToken)
|
|
req.Header.Add("Authorization", bearer)
|
|
|
|
httpClient := &http.Client{}
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
|
return nil, fmt.Errorf(resp.Status)
|
|
}
|
|
|
|
return resp, nil
|
|
}
|