|
8 | 8 | "encoding/json" |
9 | 9 | "errors" |
10 | 10 | "fmt" |
| 11 | + "io" |
11 | 12 | "log/slog" |
12 | 13 | "net/http" |
13 | 14 | "os" |
@@ -339,14 +340,15 @@ func OkResponder(allowedCodes ...int) Responder { |
339 | 340 |
|
340 | 341 | func (c *TedgeAPIClient) Do(req *http.Request, responders ...Responder) (*Response, error) { |
341 | 342 | resp, err := c.Client.Do(req) |
| 343 | + if err != nil { |
| 344 | + return nil, err |
| 345 | + } |
342 | 346 | wrappedResponse := NewResponse(resp) |
343 | 347 |
|
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 |
350 | 352 | } |
351 | 353 | } |
352 | 354 |
|
@@ -452,17 +454,26 @@ func (c *TedgeAPIClient) GetEntityTwin(ctx context.Context, target Target, name |
452 | 454 |
|
453 | 455 | type Response struct { |
454 | 456 | RawResponse *http.Response |
| 457 | + Body []byte |
455 | 458 | } |
456 | 459 |
|
457 | 460 | 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 | + } |
458 | 466 | return &Response{ |
459 | 467 | RawResponse: r, |
| 468 | + Body: body, |
460 | 469 | } |
461 | 470 | } |
462 | 471 |
|
463 | 472 | 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) |
466 | 477 | } |
467 | 478 |
|
468 | 479 | // IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false. |
|
0 commit comments