74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
|
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() {
|
||
|
weather.nextRefresh += 10
|
||
|
go weather.getData()
|
||
|
}
|
||
|
|
||
|
parts := strings.Split(weather.lastResponse, "\n")
|
||
|
|
||
|
if len(parts) > 6 {
|
||
|
return parts[:len(parts)-5]
|
||
|
}
|
||
|
|
||
|
return []string{}
|
||
|
}
|
||
|
|
||
|
func (weather *Weather) getData() {
|
||
|
myWeather, err := weather.getWeather()
|
||
|
|
||
|
if err == nil {
|
||
|
weather.lastResponse = myWeather
|
||
|
weather.nextRefresh = time.Now().Unix() + weather.Config.Weather.RefreshDelay
|
||
|
} else {
|
||
|
// log.Fatal(err)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
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
|
||
|
}
|