Skip to content

Commit

Permalink
review
Browse files Browse the repository at this point in the history
  • Loading branch information
ldez committed May 5, 2023
1 parent e2eda32 commit f1035a4
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions providers/dns/beget/internal/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"net/http"
"net/url"
"time"

"github.com/go-acme/lego/v4/providers/dns/internal/errutils"
)

const defaultBaseURL = "https://api.beget.com/api/"
Expand Down Expand Up @@ -74,7 +76,7 @@ func (c Client) doRequest(ctx context.Context, data any, fragments ...string) (*

inputData, err := json.Marshal(data)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to mashall input data: %w", err)
}

query := endpoint.Query()
Expand All @@ -87,41 +89,42 @@ func (c Client) doRequest(ctx context.Context, data any, fragments ...string) (*

req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), http.NoBody)
if err != nil {
return nil, fmt.Errorf("failed to create input data: %w", err)
return nil, fmt.Errorf("unable to create request: %w", err)
}

resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
return nil, errutils.NewHTTPDoError(req, err)
}

defer func() { _ = resp.Body.Close() }()

if resp.StatusCode/100 != 2 {
all, errB := io.ReadAll(resp.Body)
if errB != nil {
return nil, fmt.Errorf("API error, status code: %d", resp.StatusCode)
}

var apiResp APIResponse
errB = json.Unmarshal(all, &apiResp)
if errB != nil {
return nil, fmt.Errorf("API error, status code: %d, %s", resp.StatusCode, string(all))
}

return nil, fmt.Errorf("%w, status code: %d", apiResp, resp.StatusCode)
return nil, parseError(req, resp)
}

raw, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
return nil, errutils.NewReadResponseError(req, resp.StatusCode, err)
}

var apiResp APIResponse
err = json.Unmarshal(raw, &apiResp)
if err != nil {
return nil, err
return nil, errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
}

return &apiResp, nil
}

func parseError(req *http.Request, resp *http.Response) error {
raw, _ := io.ReadAll(resp.Body)

var apiResp APIResponse
err := json.Unmarshal(raw, &apiResp)
if err != nil {
return errutils.NewUnexpectedStatusCodeError(req, resp.StatusCode, raw)
}

return fmt.Errorf("[status code %d] %w", resp.StatusCode, apiResp)
}

0 comments on commit f1035a4

Please sign in to comment.