From 1a2ab41ae7140039c2fb2e5054038219c3e51da0 Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Sun, 4 Oct 2020 16:10:16 +0200 Subject: Move weather code into own package --- weather/weather.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 weather/weather.go (limited to 'weather') diff --git a/weather/weather.go b/weather/weather.go new file mode 100644 index 0000000..d60e22c --- /dev/null +++ b/weather/weather.go @@ -0,0 +1,57 @@ +// Package weather provides functions to retrieve eweather forecast data from yr.no +package weather + +import ( + "encoding/xml" + "net/http" + "time" +) + +func toTime(s string) time.Time { + t, _ := time.Parse("2006-01-02T15:04:05", s) + return t +} + +type Temperature struct { + Value int `xml:"value,attr"` + Unit string `xml:"unit,attr"` +} + +type Weather struct { + Temp Temperature `xml:"temperature"` + Symbol struct { + Var string `xml:"var,attr"` + } `xml:"symbol"` + From string `xml:"from,attr"` + URL string + Icon string +} + +func (w *Weather) prepIcon() { + w.Icon = "http://symbol.yr.no/grafikk/sym/b100/" + w.Symbol.Var + ".png" +} + +type weatherdata struct { + Forecast []*Weather `xml:"forecast>tabular>time"` +} + +func CurrentWeather(place string) (Weather, error) { + url := "http://www.yr.no/place/" + place + "/forecast_hour_by_hour.xml" + resp, err := http.Get(url) + if err != nil { + return Weather{}, err + } + defer resp.Body.Close() + + var wd weatherdata + dec := xml.NewDecoder(resp.Body) + if err := dec.Decode(&wd); err != nil { + return Weather{}, err + } + + w := wd.Forecast[0] + w.URL = "http://www.yr.no/place/" + place + w.prepIcon() + + return *w, nil +} -- cgit v1.2.3-70-g09d2