2019-07-21 02:00:04 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2019-07-24 02:43:23 +00:00
|
|
|
"bytes"
|
2019-07-21 02:00:04 +00:00
|
|
|
"encoding/json"
|
2019-07-24 02:43:23 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2019-07-21 02:00:04 +00:00
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// CheckError checks if an error occurred (it's not nil)
|
|
|
|
func CheckError(err error) {
|
|
|
|
if err != nil {
|
2019-07-24 02:43:23 +00:00
|
|
|
log.Fatalln(fmt.Sprintf("Error: %s", err.Error()))
|
2019-07-21 02:00:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func CheckResponseForErrors(resp *http.Response) error {
|
|
|
|
if 300 <= resp.StatusCode {
|
2019-07-24 02:43:23 +00:00
|
|
|
// Guess it's a GenericError
|
2019-07-21 02:00:04 +00:00
|
|
|
respBody := GenericError{}
|
|
|
|
err := json.NewDecoder(resp.Body).Decode(&respBody)
|
|
|
|
if err != nil {
|
2019-07-24 02:43:23 +00:00
|
|
|
// It's not a GenericError
|
|
|
|
bodyBytes, err := ioutil.ReadAll(resp.Body)
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
resp.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
|
|
|
|
return errors.New(string(bodyBytes))
|
2019-07-21 02:00:04 +00:00
|
|
|
}
|
|
|
|
return &respBody
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|