Skip to content

Commit

Permalink
make http client more robust
Browse files Browse the repository at this point in the history
  • Loading branch information
nilic committed Jul 25, 2023
1 parent cdaf9e5 commit 15745c2
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package client
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
Expand Down Expand Up @@ -47,14 +48,27 @@ func (c *Client) NewRequest(path string) (*http.Request, error) {
}

func (c *Client) Do(req *http.Request, v any) error {
resp, err := c.httpClient.Do(req)
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("invoking API: %w", err)
}

defer resp.Body.Close()
if res == nil {
return fmt.Errorf("empty response from %s", req.URL.RequestURI())
}

body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("reading API response: %w", err)
}

defer res.Body.Close()

if res.StatusCode != http.StatusOK {
return fmt.Errorf("calling %s:\nstatus: %s\nresponseData: %s", req.URL.RequestURI(), res.Status, body)
}

err = json.NewDecoder(resp.Body).Decode(v)
err = json.Unmarshal(body, v)

if err != nil {
return fmt.Errorf("reading response from %s %s: %s", req.Method, req.URL.RequestURI(), err)
Expand Down

0 comments on commit 15745c2

Please sign in to comment.