Skip to content

Commit

Permalink
Ignore response body during HEAD request error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
vntw committed Apr 16, 2024
1 parent 1fb53be commit fa67eee
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
14 changes: 12 additions & 2 deletions gitlab.go
Expand Up @@ -953,8 +953,13 @@ type ErrorResponse struct {

func (e *ErrorResponse) Error() string {
path, _ := url.QueryUnescape(e.Response.Request.URL.Path)
u := fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path)
return fmt.Sprintf("%s %s: %d %s", e.Response.Request.Method, u, e.Response.StatusCode, e.Message)
url := fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path)
str := fmt.Sprintf("%s %s: %d", e.Response.Request.Method, url, e.Response.StatusCode)
if e.Message != "" {
str += " " + e.Message
}

return str
}

// CheckResponse checks the API response for errors, and returns them if present.
Expand All @@ -965,6 +970,11 @@ func CheckResponse(r *http.Response) error {
}

errorResponse := &ErrorResponse{Response: r}

if r.Request.Method == http.MethodHead {
return errorResponse
}

data, err := io.ReadAll(r.Body)
if err == nil && data != nil {
errorResponse.Body = data
Expand Down
29 changes: 29 additions & 0 deletions gitlab_test.go
Expand Up @@ -203,6 +203,35 @@ func TestCheckResponseOnUnknownErrorFormat(t *testing.T) {
}
}

func TestCheckResponseOnHeadRequestError(t *testing.T) {
c, err := NewClient("")
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}

req, err := c.NewRequest(http.MethodHead, "test", nil, nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}

resp := &http.Response{
Request: req.Request,
StatusCode: http.StatusNotFound,
Body: nil,
}

errResp := CheckResponse(resp)
if errResp == nil {
t.Fatal("Expected error response.")
}

want := "HEAD https://gitlab.com/api/v4/test: 404"

if errResp.Error() != want {
t.Errorf("Expected error: %s, got %s", want, errResp.Error())
}
}

func TestRequestWithContext(t *testing.T) {
c, err := NewClient("")
if err != nil {
Expand Down

0 comments on commit fa67eee

Please sign in to comment.