Skip to content

Commit

Permalink
Remove validate response status code with expected one
Browse files Browse the repository at this point in the history
  • Loading branch information
miry committed Sep 15, 2022
1 parent b26c4ac commit bf379c2
Showing 1 changed file with 10 additions and 16 deletions.
26 changes: 10 additions & 16 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,27 +213,23 @@ func (client *Client) ResetState() error {
}

func (c *Client) get(path string) ([]byte, error) {
return c.send("GET", path, nil, http.StatusOK)
return c.send("GET", path, nil)
}

func (c *Client) post(path string, body io.Reader) ([]byte, error) {
return c.send("POST", path, body, http.StatusCreated)
return c.send("POST", path, body)
}

func (c *Client) patch(path string, body io.Reader) ([]byte, error) {
return c.send("PATCH", path, body, http.StatusOK)
return c.send("PATCH", path, body)
}

func (c *Client) delete(path string) error {
_, err := c.send("DELETE", path, nil, http.StatusNoContent)
if err != nil {
return err
}

return nil
_, err := c.send("DELETE", path, nil)
return err
}

func (c *Client) send(verb, path string, body io.Reader, success_code int) ([]byte, error) {
func (c *Client) send(verb, path string, body io.Reader) ([]byte, error) {
req, err := http.NewRequest(verb, c.endpoint+path, body)
if err != nil {
return nil, err
Expand All @@ -247,7 +243,7 @@ func (c *Client) send(verb, path string, body io.Reader, success_code int) ([]by
return nil, fmt.Errorf("fail to request: %w", err)
}

err = c.validateResponse(resp, success_code)
err = c.validateResponse(resp)
if err != nil {
return nil, err
}
Expand All @@ -261,24 +257,22 @@ func (c *Client) send(verb, path string, body io.Reader, success_code int) ([]by
return result, nil
}

func (c *Client) validateResponse(resp *http.Response, expectedCode int) error {
func (c *Client) validateResponse(resp *http.Response) error {
if resp.StatusCode < 300 && resp.StatusCode >= 200 {
return nil
}

apiError := new(ApiError)
result, err := io.ReadAll(resp.Body)
err := json.NewDecoder(resp.Body).Decode(&apiError)
if err != nil {
return err
}
resp.Body.Close()

err = json.Unmarshal(result, apiError)
if err != nil {
apiError.Message = fmt.Sprintf(
"Unexpected response code %d, expected %d",
"Unexpected response code %d",
resp.StatusCode,
expectedCode,
)
apiError.Status = resp.StatusCode
}
Expand Down

0 comments on commit bf379c2

Please sign in to comment.