mirror of
https://github.com/prymitive/karma
synced 2026-05-07 03:26:52 +00:00
Add http transport reader
Copy code from GetJSONFromURL into a http reader constructor
This commit is contained in:
@@ -50,3 +50,47 @@ func GetJSONFromURL(url string, timeout time.Duration, target interface{}) error
|
||||
|
||||
return json.NewDecoder(reader).Decode(target)
|
||||
}
|
||||
|
||||
type httpReader struct {
|
||||
URL string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func newHTTPReader(url string, timeout time.Duration) (*io.ReadCloser, error) {
|
||||
hr := httpReader{URL: url, Timeout: timeout}
|
||||
|
||||
log.Infof("GET %s timeout=%s", hr.URL, hr.Timeout)
|
||||
|
||||
c := &http.Client{
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", hr.URL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Add("Accept-Encoding", "gzip")
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Request to Alertmanager failed with %s", resp.Status)
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
var reader io.ReadCloser
|
||||
switch resp.Header.Get("Content-Encoding") {
|
||||
case "gzip":
|
||||
reader, err = gzip.NewReader(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to decode gzipped content: %s", err.Error())
|
||||
}
|
||||
defer reader.Close()
|
||||
default:
|
||||
reader = resp.Body
|
||||
}
|
||||
return &reader, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user