forked from surol/speedtest-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeedtest.go
103 lines (87 loc) · 2.21 KB
/
speedtest.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
package main
import (
"github.com/surol/speedtest-cli/speedtest"
"fmt"
"os"
"flag"
"log"
"time"
)
func version() {
fmt.Print(speedtest.Version)
}
func usage() {
fmt.Fprint(os.Stderr, "Command line interface for testing internet bandwidth using speedtest.net.\n\n")
flag.PrintDefaults()
}
func main() {
opts := speedtest.ParseOpts()
switch {
case opts.Help:
usage()
return
case opts.Version:
version()
return
}
client := speedtest.NewClient(opts)
if opts.List {
servers, err := client.AllServers()
if err != nil {
log.Fatalf("Failed to load server list: %v\n", err)
}
fmt.Println(servers)
return
}
config, err := client.Config()
if err != nil {
log.Fatal(err)
}
client.Log("Testing from %s (%s)...\n", config.Client.ISP, config.Client.IP)
server := selectServer(opts, client);
downloadSpeed := server.DownloadSpeed()
reportSpeed(opts, "Download", downloadSpeed)
uploadSpeed := server.UploadSpeed()
reportSpeed(opts, "Upload", uploadSpeed)
}
func reportSpeed(opts *speedtest.Opts, prefix string, speed int) {
if opts.SpeedInBytes {
fmt.Printf("%s: %.2f MiB/s\n", prefix, float64(speed) / (1 << 20))
} else {
fmt.Printf("%s: %.2f Mib/s\n", prefix, float64(speed) / (1 << 17))
}
}
func selectServer(opts *speedtest.Opts, client speedtest.Client) (selected *speedtest.Server) {
if opts.Server != 0 {
servers, err := client.AllServers()
if err != nil {
log.Fatal("Failed to load server list: %v\n", err)
return nil
}
selected = servers.Find(opts.Server)
if selected == nil {
log.Fatalf("Server not found: %d\n", opts.Server)
return nil
}
selected.MeasureLatency(speedtest.DefaultLatencyMeasureTimes, speedtest.DefaultErrorLatency)
} else {
servers, err := client.ClosestServers()
if err != nil {
log.Fatal("Failed to load server list: %v\n", err)
return nil
}
selected = servers.MeasureLatencies(
speedtest.DefaultLatencyMeasureTimes,
speedtest.DefaultErrorLatency).First()
}
if opts.Quiet {
log.Printf("Ping: %d ms\n", selected.Latency / time.Millisecond)
} else {
client.Log("Hosted by %s (%s) [%.2f km]: %d ms\n",
selected.Sponsor,
selected.Name,
selected.Distance,
selected.Latency / time.Millisecond)
}
return selected
}