59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package poller
|
|
|
|
import (
|
|
"go/weather/internal/web"
|
|
"go/weather/pkg/logger"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type weatherPoller struct {
|
|
client *http.Client
|
|
endpoint *url.URL
|
|
logger *logger.WeatherLogger
|
|
}
|
|
|
|
//NewWeatherPoller construct weather poller instance
|
|
func NewWeatherPoller(log *logger.WeatherLogger, remote web.ListenAddr, lat, lon float64, secretID string) Poller {
|
|
u := &url.URL{
|
|
Scheme: "https",
|
|
Path: "/data/2.5/onecall",
|
|
Host: remote.String(),
|
|
}
|
|
q := u.Query()
|
|
q.Set("lat", strconv.FormatFloat(lat, 'f', 2, 64))
|
|
q.Set("lon", strconv.FormatFloat(lon, 'f', 2, 32))
|
|
q.Set("appid", secretID)
|
|
q.Set("units", "metric")
|
|
q.Set("lang", "fr")
|
|
u.RawQuery = q.Encode()
|
|
|
|
return &weatherPoller{
|
|
client: http.DefaultClient,
|
|
endpoint: u,
|
|
logger: log,
|
|
}
|
|
}
|
|
|
|
//Poll retrieve weather information
|
|
func (w *weatherPoller) Poll() io.ReadCloser {
|
|
r, err := w.client.Get(w.endpoint.String())
|
|
w.logger.Info("HTTP poll to openweathermap",
|
|
zap.Int("http.response.status_code", r.StatusCode),
|
|
zap.Int("http.response.body.bytes", int(r.ContentLength)),
|
|
)
|
|
w.handleError(err)
|
|
return r.Body
|
|
}
|
|
|
|
//handleError generic fatal error
|
|
func (w *weatherPoller) handleError(err error) {
|
|
if err != nil {
|
|
w.logger.Error("Poller error", zap.Error(err))
|
|
}
|
|
}
|