yr/internal/met/met.go

56 lines
1 KiB
Go
Raw Normal View History

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
}