weather.go (1866B)
1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "log" 7 "net/http" 8 9 "github.com/gogpu/gg" 10 "github.com/gogpu/gg/text" 11 ) 12 13 const ( 14 // Weather for Calverley 15 weatherApiUrl = "https://api.open-meteo.com/v1/forecast?latitude=58.829906&longitude=-1.687577&daily=temperature_2m_max,temperature_2m_min,precipitation_hours&models=ukmo_seamless&forecast_days=3" 16 outfile = "images/weather.png" 17 ) 18 19 func main() { 20 err := domain(); 21 if err != nil { 22 log.Fatal(err) 23 } 24 } 25 26 func domain() error { 27 res, err := http.DefaultClient.Get(weatherApiUrl) 28 if err != nil { 29 return err 30 } 31 if res.StatusCode < 200 || res.StatusCode >= 400 { 32 return fmt.Errorf("Error status code from %s: %d %s", weatherApiUrl, res.StatusCode, res.Status) 33 } 34 var weather WeatherApiRes 35 err = json.NewDecoder(res.Body).Decode(&weather) 36 if err != nil { 37 return err 38 } 39 40 dc := gg.NewContext(600, 800) 41 defer dc.Close() 42 43 dc.ClearWithColor(gg.White) 44 dc.SetColor(gg.Black) 45 46 // Divider lines 47 dc.SetLineWidth(5) 48 dc.DrawLine(0, 233, 600, 233) 49 dc.DrawLine(0, 466, 600, 466) 50 51 source, err := text.NewFontSourceFromFile("fonts/ARIAL.TTF") 52 if err != nil { 53 return err 54 } 55 defer source.Close() 56 dc.SetFont(source.Face(32)) 57 for ix, time := range weather.Daily.Time { 58 dc.DrawString(time, 20, float64((ix*233) + 32)) 59 dc.DrawString(fmt.Sprintf("Max %.1f°C", weather.Daily.Temp2MMax[ix]), 20, float64((ix*233) + 64)) 60 dc.DrawString(fmt.Sprintf("Min %.1f°C", weather.Daily.Temp2MMin[ix]), 20, float64((ix*233) + 96)) 61 } 62 63 err = dc.SavePNG(outfile) 64 if err != nil { 65 return err 66 } 67 return nil 68 } 69 70 type WeatherApiRes struct { 71 Daily struct { 72 Time []string `json:"time"` 73 Temp2MMax []float64 `json:"temperature_2m_max"` 74 Temp2MMin []float64 `json:"temperature_2m_min"` 75 PrecipitationHours []float64 `json:"precipitation_hours"` 76 } `json:"daily"` 77 }