-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (72 loc) · 1.62 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os/exec"
"sync"
"time"
)
type Container struct {
mu sync.Mutex
result *SpeedtestResult
}
func (c *Container) Set(result *SpeedtestResult) {
c.mu.Lock()
defer c.mu.Unlock()
c.result = result
}
func (c *Container) Get() *SpeedtestResult {
c.mu.Lock()
defer c.mu.Unlock()
if c.result == nil {
return &SpeedtestResult{
Download: 0,
Upload: 0,
Ping: 0,
Timestamp: time.Now().UTC().Format(time.RFC3339),
}
}
return c.result
}
type SpeedtestResult struct {
Download float64 `json:"download"`
Upload float64 `json:"upload"`
Ping float64 `json:"ping"`
Timestamp string `json:"timestamp"`
}
func NewSpeedtestResult() *SpeedtestResult {
cmd := exec.Command("speedtest", "--accept-license", "--accept-gdpr", "-fjson")
// Read output
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
panic(err)
}
var output map[string]any
if err := json.Unmarshal(stdout, &output); err != nil {
fmt.Println(err)
panic(err)
}
return &SpeedtestResult{
Download: output["download"].(map[string]any)["bandwidth"].(float64),
Upload: output["upload"].(map[string]any)["bandwidth"].(float64),
Ping: output["ping"].(map[string]any)["latency"].(float64),
Timestamp: output["timestamp"].(string),
}
}
func main() {
c := &Container{}
go func() {
for {
result := NewSpeedtestResult()
c.Set(result)
time.Sleep(5 * time.Minute)
}
}()
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
result := c.Get()
json.NewEncoder(w).Encode(result)
})
http.ListenAndServe(":80", nil)
}