refactor: add limitreader to Client.do

This commit is contained in:
Dawid Wysokiński 2023-04-10 10:30:15 +02:00
parent 3f333282a3
commit de132453db
Signed by: Kichiyaki
GPG Key ID: B5445E357FB8B892
2 changed files with 15 additions and 11 deletions

View File

@ -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)

12
main.go
View File

@ -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