From 012bd95cbbcd8e8b3d47ba4ca2d28b145decff5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20H=C3=A5rek=20Andreassen?= Date: Tue, 24 Sep 2024 22:18:08 +0200 Subject: [PATCH] refactor: Use query params instead of sprintf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tim HĂ„rek Andreassen --- internal/met/met.go | 10 +++++++++- internal/met/met_test.go | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/internal/met/met.go b/internal/met/met.go index 9482d9b..7c14ea0 100644 --- a/internal/met/met.go +++ b/internal/met/met.go @@ -22,13 +22,21 @@ func New(siteName string) (*Met, error) { } func (m *Met) Forecast(lat, lon float64, alt *int) (*LocationForecastResult, error) { - url := fmt.Sprintf("https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=%.4f&lon=%.4f&altitude=%d", lat, lon, alt) + url := "https://api.met.no/weatherapi/locationforecast/2.0/complete" req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } + q := req.URL.Query() + q.Add("lat", fmt.Sprintf("%.4f", lat)) + q.Add("lon", fmt.Sprintf("%.4f", lon)) + if alt != nil { + q.Add("altitude", fmt.Sprintf("%d", alt)) + } + req.URL.RawQuery = q.Encode() + req.Header.Set("User-Agent", m.siteName) resp, err := http.DefaultClient.Do(req) if err != nil { diff --git a/internal/met/met_test.go b/internal/met/met_test.go index f880186..8caf876 100644 --- a/internal/met/met_test.go +++ b/internal/met/met_test.go @@ -25,7 +25,7 @@ func TestForecast(t *testing.T) { f, err := c.Forecast(60.389444, 5.33, nil) assert.NoError(err) coords := f.Geometry.Coordinates - assert.Equal([]float64{5.33, 60.3894, 0}, coords) + assert.Equal([]float64{5.33, 60.3894, 2}, coords) _, err = c.Forecast(10000.0, 10000.33, nil) assert.Error(err)