From 99686a12d21eeb2d7b60d300364ece7d642d03b9 Mon Sep 17 00:00:00 2001 From: Elis Hirwing Date: Sat, 4 Nov 2017 12:25:16 +0100 Subject: [PATCH] Add weather module --- src/statusscreen/Config.go | 4 +++ src/statusscreen/Weather.go | 62 +++++++++++++++++++++++++++++++++++++ status.sample.toml | 4 +++ 3 files changed, 70 insertions(+) create mode 100644 src/statusscreen/Weather.go diff --git a/src/statusscreen/Config.go b/src/statusscreen/Config.go index ddbb3b8..4c0a208 100644 --- a/src/statusscreen/Config.go +++ b/src/statusscreen/Config.go @@ -11,4 +11,8 @@ type Config struct { Clock struct { TimeFormat string } + Weather struct { + URL string + RefreshDelay int64 + } } diff --git a/src/statusscreen/Weather.go b/src/statusscreen/Weather.go new file mode 100644 index 0000000..4f00ba2 --- /dev/null +++ b/src/statusscreen/Weather.go @@ -0,0 +1,62 @@ +package statusscreen + +import ( + "io/ioutil" + "net/http" + "strings" + "time" +) + +// Weather is my Weather struct +type Weather struct { + Config *Config + lastResponse string + nextRefresh int64 +} + +// GetOutput returns a rendered result of this module +func (weather *Weather) GetOutput() []string { + if weather.nextRefresh <= time.Now().Unix() { + myWeather, err := weather.getWeather() + + if err == nil { + weather.lastResponse = myWeather + weather.nextRefresh = time.Now().Unix() + weather.Config.Weather.RefreshDelay + } else { + // log.Fatal(err) + } + } + + return strings.Split(weather.lastResponse, "\n") +} + +func (weather *Weather) getWeather() (string, error) { + // Set up http client to fetch weather + client := &http.Client{ + Timeout: time.Second * 5, + } + + // Set up request + req, err := http.NewRequest("GET", weather.Config.Weather.URL, nil) + if err != nil { + return "", err + } + + // Set curl user agent + req.Header.Set("User-Agent", "curl/7.52.1") + + // Do request + resp, err := client.Do(req) + if err != nil { + return "", err + } + + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", err + } + + return string(body), nil +} diff --git a/status.sample.toml b/status.sample.toml index 6d029a6..3c6cb66 100644 --- a/status.sample.toml +++ b/status.sample.toml @@ -6,3 +6,7 @@ APIURL = "https://api.sl.se/api2/realtimedeparturesV4.json?key=%s&siteid=%d&time [Clock] TimeFormat = "15:04:05" + +[Weather] +URL = "http://wttr.in/" +RefreshDelay = 1800