yr/internal/met/met.go
Tim Hårek Andreassen 86d8f74a99
test: Add initial tests for forecast
Signed-off-by: Tim Hårek Andreassen <tim@harek.no>
2024-09-24 22:01:20 +02:00

55 lines
1 KiB
Go

package met
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type Met struct {
siteName string
}
func New(siteName string) (*Met, error) {
if siteName == "" {
return nil, fmt.Errorf("`siteName` must be defined.")
}
return &Met{
siteName: siteName,
}, nil
}
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)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", m.siteName)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
forecast := LocationforecastResult{}
err = json.Unmarshal(body, &forecast)
if err != nil {
return nil, err
}
return &forecast, nil
}