From c8b88ccef5c9fed0ca7662ff2c9062a9cf7084b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferdinand=20M=C3=BCtsch?= Date: Wed, 19 Jul 2023 18:36:27 +0200 Subject: [PATCH] chore: log response body of failed http requests --- utils/http.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/utils/http.go b/utils/http.go index 9dad46a..ec7b72d 100644 --- a/utils/http.go +++ b/utils/http.go @@ -1,8 +1,10 @@ package utils import ( + "bytes" "errors" "fmt" + "io" "net/http" "regexp" "strconv" @@ -92,7 +94,15 @@ func RaiseForStatus(res *http.Response, err error) (*http.Response, error) { return res, err } if res.StatusCode >= 400 { - return res, fmt.Errorf("got response status %d for '%s %s'", res.StatusCode, res.Request.Method, res.Request.URL.String()) + message := "" + contentType := res.Header.Get("content-type") + if strings.HasPrefix(contentType, "text/") || strings.HasPrefix(contentType, "application/json") { + body, _ := io.ReadAll(res.Body) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewBuffer(body)) + message = string(body) + } + return res, fmt.Errorf("got response status %d for '%s %s' - %s", res.StatusCode, res.Request.Method, res.Request.URL.String(), message) } return res, nil }