/
widget.go
67 lines (51 loc) · 1.41 KB
/
widget.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package prettyweather
import (
"io"
"net/http"
"strings"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/view"
"github.com/wtfutil/wtf/wtf"
)
type Widget struct {
view.TextWidget
result string
settings *Settings
}
func NewWidget(tviewApp *tview.Application, redrawChan chan bool, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, redrawChan, nil, settings.Common),
settings: settings,
}
return &widget
}
func (widget *Widget) Refresh() {
widget.prettyWeather()
widget.Redraw(func() (string, string, bool) { return widget.CommonSettings().Title, widget.result, false })
}
// this method reads the config and calls wttr.in for pretty weather
func (widget *Widget) prettyWeather() {
client := &http.Client{}
city := widget.settings.city
unit := widget.settings.unit
view := widget.settings.view
req, err := http.NewRequest("GET", "https://wttr.in/"+city+"?"+view+"?"+unit, http.NoBody)
if err != nil {
widget.result = err.Error()
return
}
req.Header.Set("Accept-Language", widget.settings.language)
req.Header.Set("User-Agent", "curl")
response, err := client.Do(req)
if err != nil {
widget.result = err.Error()
return
}
defer func() { _ = response.Body.Close() }()
contents, err := io.ReadAll(response.Body)
if err != nil {
widget.result = err.Error()
return
}
widget.result = strings.TrimSpace(wtf.ASCIItoTviewColors(string(contents)))
}