Skip to content

Commit 3b2a896

Browse files
authored
Merge pull request #154 from thin-edge/fix-unclosed-responses
fix: ensure body is always closed before returning
2 parents 1231ed3 + 9c99790 commit 3b2a896

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

pkg/tedge/tedge.go

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"encoding/json"
99
"errors"
1010
"fmt"
11+
"io"
1112
"log/slog"
1213
"net/http"
1314
"os"
@@ -339,14 +340,15 @@ func OkResponder(allowedCodes ...int) Responder {
339340

340341
func (c *TedgeAPIClient) Do(req *http.Request, responders ...Responder) (*Response, error) {
341342
resp, err := c.Client.Do(req)
343+
if err != nil {
344+
return nil, err
345+
}
342346
wrappedResponse := NewResponse(resp)
343347

344-
if err == nil {
345-
for _, responder := range responders {
346-
wrappedResponse, err = responder(wrappedResponse, err)
347-
if err != nil {
348-
break
349-
}
348+
for _, responder := range responders {
349+
wrappedResponse, err = responder(wrappedResponse, err)
350+
if err != nil {
351+
break
350352
}
351353
}
352354

@@ -452,17 +454,26 @@ func (c *TedgeAPIClient) GetEntityTwin(ctx context.Context, target Target, name
452454

453455
type Response struct {
454456
RawResponse *http.Response
457+
Body []byte
455458
}
456459

457460
func NewResponse(r *http.Response) *Response {
461+
var body []byte
462+
if r != nil && r.Body != nil {
463+
body, _ = io.ReadAll(r.Body)
464+
_ = r.Body.Close()
465+
}
458466
return &Response{
459467
RawResponse: r,
468+
Body: body,
460469
}
461470
}
462471

463472
func (r *Response) Decode(v any) error {
464-
defer r.RawResponse.Body.Close()
465-
return json.NewDecoder(r.RawResponse.Body).Decode(v)
473+
if len(r.Body) == 0 {
474+
return fmt.Errorf("response body is empty")
475+
}
476+
return json.Unmarshal(r.Body, v)
466477
}
467478

468479
// IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.

0 commit comments

Comments
 (0)