Skip to content

Commit 9b0e206

Browse files
committed
refining retry loop and logging
1 parent 590249c commit 9b0e206

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

internal/weather/weather.go

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -261,17 +261,24 @@ func (w *Location) fetchWeatherData(ctx context.Context, endpoint string, result
261261
req.Header.Add("Accept", "application/json")
262262

263263
var res *http.Response
264-
for attempts := range 3 {
264+
for attempt := range 3 {
265265
res, err = client.Do(req)
266266
if err == nil {
267267
break
268268
}
269-
log.Error("Request failed, retrying", "attempt", attempts, "url", apiURLForLog.String(), "err", err)
269+
// Log attempts as 1-based for clarity
270+
log.Error("Request failed, retrying", "attempt", attempt+1, "url", apiURLForLog.String(), "err", err)
270271

271-
time.Sleep(time.Duration(1<<attempts) * time.Second)
272+
backoff := time.Duration(1<<attempt) * time.Second
273+
select {
274+
case <-ctx.Done():
275+
return ctx.Err()
276+
case <-time.After(backoff):
277+
}
272278
}
279+
273280
if err != nil {
274-
log.Error("Request failed after retries", "err", err)
281+
log.Error("Request failed after retries", "url", apiURLForLog.String(), "err", err)
275282
return err
276283
}
277284

@@ -288,16 +295,10 @@ func (w *Location) fetchWeatherData(ctx context.Context, endpoint string, result
288295
return err
289296
}
290297

291-
responseBody, err := io.ReadAll(res.Body)
292-
if err != nil {
293-
log.Error("reading response body", "url", apiURLForLog.String(), "err", err)
294-
return err
295-
}
296-
297-
unmarshalErr := json.Unmarshal(responseBody, result)
298-
if unmarshalErr != nil {
299-
log.Error("fetchWeatherData", "err", unmarshalErr)
300-
return unmarshalErr
298+
decErr := json.NewDecoder(res.Body).Decode(result)
299+
if decErr != nil {
300+
log.Error("fetchWeatherData", "err", decErr)
301+
return decErr
301302
}
302303

303304
return nil

0 commit comments

Comments
 (0)