yr/internal/met/met.go

52 lines
946 B
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 float64, 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()
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
}