012bd95cbb
Signed-off-by: Tim Hårek Andreassen <tim@harek.no>
63 lines
1.1 KiB
Go
63 lines
1.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 := "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 {
|
|
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
|
|
}
|