1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

chore: log response body of failed http requests

This commit is contained in:
Ferdinand Mütsch 2023-07-19 18:36:27 +02:00
parent 5f1ca4ed69
commit c8b88ccef5

View File

@ -1,8 +1,10 @@
package utils package utils
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"io"
"net/http" "net/http"
"regexp" "regexp"
"strconv" "strconv"
@ -92,7 +94,15 @@ func RaiseForStatus(res *http.Response, err error) (*http.Response, error) {
return res, err return res, err
} }
if res.StatusCode >= 400 { 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 := "<body omitted or empty>"
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 return res, nil
} }