From 5003ccc3db5315bca20322225044820f6114c058 Mon Sep 17 00:00:00 2001 From: Vilen Topchii <32271530+vtopc@users.noreply.github.com> Date: Tue, 10 Dec 2024 20:04:43 +0200 Subject: [PATCH] DE-1373 Get rid of defers in a loop (#362) --- .golangci.yml | 1 - httphelpers.go | 48 ++++++++++++++++++++++++++++++------------------ 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index f5403dc..b74f6ac 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -34,7 +34,6 @@ linters-settings: - style disabled-checks: - singleCaseSwitch - - deferInLoop # TODO(DE-1373): enable - hugeParam # TODO(v5): enable? - sprintfQuotedString # noisy # TODO: enable - exitAfterDefer # TODO: enable? diff --git a/httphelpers.go b/httphelpers.go index e164f67..ccf7694 100644 --- a/httphelpers.go +++ b/httphelpers.go @@ -188,35 +188,47 @@ func (f *FormDataPayload) getPayloadBuffer() (*bytes.Buffer, error) { } for _, file := range f.Files { - tmp, err := writer.CreateFormFile(file.key, path.Base(file.value)) - if err != nil { - return nil, err - } + err := func() error { + tmp, err := writer.CreateFormFile(file.key, path.Base(file.value)) + if err != nil { + return err + } - fp, err := os.Open(file.value) - if err != nil { - return nil, err - } + fp, err := os.Open(file.value) + if err != nil { + return err + } - // TODO(DE-1373): defer in a loop: - defer fp.Close() + defer fp.Close() - _, err = io.Copy(tmp, fp) + _, err = io.Copy(tmp, fp) + if err != nil { + return err + } + + return nil + }() if err != nil { return nil, err } } for _, file := range f.ReadClosers { - tmp, err := writer.CreateFormFile(file.key, file.name) - if err != nil { - return nil, err - } + err := func() error { + tmp, err := writer.CreateFormFile(file.key, file.name) + if err != nil { + return err + } + + defer file.value.Close() - // TODO(DE-1373): defer in a loop: - defer file.value.Close() + _, err = io.Copy(tmp, file.value) + if err != nil { + return err + } - _, err = io.Copy(tmp, file.value) + return nil + }() if err != nil { return nil, err }