-
-
Notifications
You must be signed in to change notification settings - Fork 800
/
widget.go
107 lines (88 loc) · 2.42 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package ipinfo
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"text/template"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/wtf"
)
type Widget struct {
wtf.TextWidget
result string
settings *Settings
}
type ipinfo struct {
Ip string `json:"ip"`
Hostname string `json:"hostname"`
City string `json:"city"`
Region string `json:"region"`
Country string `json:"country"`
Coordinates string `json:"loc"`
PostalCode string `json:"postal"`
Organization string `json:"org"`
}
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: wtf.NewTextWidget(app, settings.common, false),
settings: settings,
}
widget.View.SetWrap(false)
return &widget
}
func (widget *Widget) Refresh() {
widget.ipinfo()
widget.TextWidget.Redraw(widget.CommonSettings().Title, widget.result, false)
}
//this method reads the config and calls ipinfo for ip information
func (widget *Widget) ipinfo() {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://ipinfo.io/", nil)
if err != nil {
widget.result = err.Error()
return
}
req.Header.Set("User-Agent", "curl")
response, err := client.Do(req)
if err != nil {
widget.result = err.Error()
return
}
defer response.Body.Close()
var info ipinfo
err = json.NewDecoder(response.Body).Decode(&info)
if err != nil {
widget.result = err.Error()
return
}
widget.setResult(&info)
}
func (widget *Widget) setResult(info *ipinfo) {
resultTemplate, _ := template.New("ipinfo_result").Parse(
formatableText("IP", "Ip") +
formatableText("Hostname", "Hostname") +
formatableText("City", "City") +
formatableText("Region", "Region") +
formatableText("Country", "Country") +
formatableText("Coords", "Coordinates") +
formatableText("Org", "Organization"),
)
resultBuffer := new(bytes.Buffer)
resultTemplate.Execute(resultBuffer, map[string]string{
"nameColor": widget.settings.colors.name,
"valueColor": widget.settings.colors.value,
"Ip": info.Ip,
"Hostname": info.Hostname,
"City": info.City,
"Region": info.Region,
"Country": info.Country,
"Coordinates": info.Coordinates,
"PostalCode": info.PostalCode,
"Organization": info.Organization,
})
widget.result = resultBuffer.String()
}
func formatableText(key, value string) string {
return fmt.Sprintf(" [{{.nameColor}}]%8s: [{{.valueColor}}]{{.%s}}\n", key, value)
}