From de132453db040f3a433d4f77d1e5a5a64a11400d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Wysoki=C5=84ski?= Date: Mon, 10 Apr 2023 10:30:15 +0200 Subject: [PATCH] refactor: add limitreader to Client.do --- internal/infakt/client.go | 14 +++++++++----- main.go | 12 ++++++------ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/internal/infakt/client.go b/internal/infakt/client.go index 92b7840..24f7ab8 100644 --- a/internal/infakt/client.go +++ b/internal/infakt/client.go @@ -16,9 +16,7 @@ import ( const ( defaultBaseURL = "https://api.infakt.pl" defaultTimeout = 10 * time.Second - //nolint:gosec - apiKeyHeader = "X-inFakt-ApiKey" - reqPerMinute = 150 + reqPerMinute = 150 ) type Client struct { @@ -132,7 +130,7 @@ func (c *Client) GetInvoicePDF(ctx context.Context, invoiceUUID, documentType, l } if locale != "" { - values["locale"] = []string{locale} + values.Set("locale", locale) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf(endpointGetInvoicePDF, invoiceUUID)+"?"+values.Encode(), nil) @@ -172,6 +170,12 @@ func (c *Client) postJSON(ctx context.Context, url string, body any) (*http.Resp return c.do(req) } +const ( + maxErrBodySizeBytes = 250000 + //nolint:gosec + apiKeyHeader = "X-inFakt-ApiKey" +) + func (c *Client) do(req *http.Request) (*http.Response, error) { url, err := urlpkg.Parse(c.baseURL + req.URL.String()) if err != nil { @@ -191,7 +195,7 @@ func (c *Client) do(req *http.Request) (*http.Response, error) { } if resp.StatusCode >= http.StatusBadRequest { - b, _ := io.ReadAll(resp.Body) + b, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrBodySizeBytes)) _, _ = io.Copy(io.Discard, resp.Body) _ = resp.Body.Close() return nil, fmt.Errorf("request failed with status=%d and body=%s", resp.StatusCode, b) diff --git a/main.go b/main.go index c163ec5..b470636 100644 --- a/main.go +++ b/main.go @@ -55,11 +55,6 @@ func newInvoiceCmd() *cli.Command { { Name: "create", Action: func(c *cli.Context) error { - var clientOpts []infakt.ClientOption - if url := c.String("url"); url != "" { - clientOpts = append(clientOpts, infakt.WithBaseURL(url)) - } - b, err := os.ReadFile(c.Path("file")) if err != nil { return err @@ -70,7 +65,12 @@ func newInvoiceCmd() *cli.Command { return err } + var clientOpts []infakt.ClientOption + if url := c.String("url"); url != "" { + clientOpts = append(clientOpts, infakt.WithBaseURL(url)) + } client := infakt.NewClient(c.String("apiKey"), clientOpts...) + downloadInvoices := c.Bool("download") downloadPath := c.String("downloadPath") if downloadPath == "" { @@ -97,7 +97,7 @@ func newInvoiceCmd() *cli.Command { continue } - log.Printf("invoice '%s' saved on disk: %s", invoice.Number, invoicePath) + log.Printf("invoice '%s' saved on disk: '%s'", invoice.Number, invoicePath) } return nil