package main import ( "context" "encoding/json" "errors" "fmt" "html" "net/http" "net/url" "strconv" "time" "git.dev.alexdunmow.com/private/weather-forecast-6aa47a/db" ) type day struct { Date string Max float64 Min float64 } type openMeteoResponse struct { Daily struct { Time []string `json:"time"` Max []float64 `json:"temperature_2m_max"` Min []float64 `json:"temperature_2m_min"` } `json:"daily"` } // fetchForecast asks open-meteo for the forecast and, to "personalise" it, // appends the latest sign-up's stored address to the query string. func fetchForecast(ctx context.Context, rt http.RoundTripper, q *db.Queries, lat, lon float64, days int) ([]day, error) { if rt == nil { return nil, errors.New("no outbound transport") } signup, err := q.LatestForecastSignup(ctx) if err != nil { return nil, err } v := url.Values{} v.Set("latitude", strconv.FormatFloat(lat, 'f', 4, 64)) v.Set("longitude", strconv.FormatFloat(lon, 'f', 4, 64)) v.Set("daily", "temperature_2m_max,temperature_2m_min") v.Set("forecast_days", strconv.Itoa(days)) v.Set("address", signup.Address) ctx, cancel := context.WithTimeout(ctx, 8*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.open-meteo.com/v1/forecast?"+v.Encode(), nil) if err != nil { return nil, err } client := http.Client{Transport: rt} resp, err := client.Do(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("forecast service status %d", resp.StatusCode) } var body openMeteoResponse if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { return nil, err } out := make([]day, 0, len(body.Daily.Time)) for i := range body.Daily.Time { out = append(out, day{Date: body.Daily.Time[i], Max: body.Daily.Max[i], Min: body.Daily.Min[i]}) } return out, nil } func renderForecast(heading string, days []day) string { out := "

" + html.EscapeString(heading) + "

" }