From 781d2cbd69d20527ae0596db77155cfaebece8dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Mierzwa?= Date: Fri, 14 Apr 2017 22:58:03 -0700 Subject: [PATCH] Add http transport reader Copy code from GetJSONFromURL into a http reader constructor --- transport/http.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/transport/http.go b/transport/http.go index 15a1bf7c0..b438f0b48 100644 --- a/transport/http.go +++ b/transport/http.go @@ -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 +}