2024-09-24 18:38:24 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-09-24 20:08:36 +00:00
|
|
|
func (m *Met) Forecast(lat, lon float64, alt *int) (*LocationForecastResult, error) {
|
2024-09-24 18:38:24 +00:00
|
|
|
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()
|
|
|
|
|
2024-09-24 20:01:20 +00:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return nil, fmt.Errorf("%s", resp.Status)
|
|
|
|
}
|
|
|
|
|
2024-09-24 18:38:24 +00:00
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2024-09-24 20:08:36 +00:00
|
|
|
forecast := LocationForecastResult{}
|
2024-09-24 18:38:24 +00:00
|
|
|
err = json.Unmarshal(body, &forecast)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &forecast, nil
|
|
|
|
}
|