IRC bot for interacting with mazerats.jerryaldrichiii.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.0 KiB

package web
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// GetBody the body from an HTTP GET request as a []byte
func GetBody(url string, format string) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if format == "json" {
req.Header.Add("Accept", "application/json")
} else {
req.Header.Add("Accept", "text/plain")
}
res, err := client.Do(req)
if err != nil {
return []byte{}, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return []byte{}, fmt.Errorf("Request failed, '%v' received", res.StatusCode)
}
response, err := ioutil.ReadAll(res.Body)
if err != nil {
return []byte{}, err
}
if len(response) == 0 {
return []byte{}, fmt.Errorf("Empty body received from '%v'", url)
}
return response, nil
}
// GetJSON unmarshals the result of an HTTP GET request to an interface{}
func GetJSON(url string, s interface{}) error {
body, err := GetBody(url, "json")
if err != nil {
return err
}
err = json.Unmarshal(body, s)
if err != nil {
return err
}
return nil
}