Skip to content

Commit 590249c

Browse files
committed
reuse http client
1 parent 037e3ae commit 590249c

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

internal/weather/weather.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ var (
2626
weatherDataStore sync.Map
2727
defaultLocationMu sync.RWMutex
2828
defaultLocation string
29+
httpClient = &http.Client{
30+
Timeout: 10 * time.Second,
31+
}
2932
)
3033

3134
type Location struct {
@@ -248,9 +251,7 @@ func (w *Location) fetchWeatherData(ctx context.Context, endpoint string, result
248251
qLog.Set("appid", "REDACTED")
249252
apiURLForLog.RawQuery = qLog.Encode()
250253

251-
client := &http.Client{
252-
Timeout: time.Second * 10,
253-
}
254+
client := httpClient
254255
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL.String(), nil)
255256
if err != nil {
256257
log.Error(err)
@@ -277,8 +278,13 @@ func (w *Location) fetchWeatherData(ctx context.Context, endpoint string, result
277278
defer res.Body.Close()
278279

279280
if res.StatusCode < 200 || res.StatusCode >= 300 {
280-
err = fmt.Errorf("unexpected status code: %d", res.StatusCode)
281-
log.Error(err)
281+
bodyPreview, _ := io.ReadAll(io.LimitReader(res.Body, 1024))
282+
err = fmt.Errorf("unexpected status code: %d, body: %s",
283+
res.StatusCode, strings.TrimSpace(string(bodyPreview)))
284+
log.Error("OpenWeatherMap API error",
285+
"url", apiURLForLog.String(),
286+
"status", res.StatusCode,
287+
"body", string(bodyPreview))
282288
return err
283289
}
284290

@@ -317,7 +323,7 @@ func (w *Location) updateForecast(ctx context.Context) (Location, error) {
317323
if err != nil {
318324
return *w, err
319325
}
320-
w.Forecast = processForecast(newForecast, w.Weather.Timezone)
326+
w.Forecast = processForecast(newForecast, w.Timezone)
321327
return *w, nil
322328
}
323329

0 commit comments

Comments
 (0)