/
test.go
92 lines (77 loc) · 1.93 KB
/
test.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
package main
import "bytes"
import "errors"
import "fmt"
import "io"
import "net/http"
import "strings"
import "time"
const downloadUrl = "http://test.ntwrk.waits.io/download"
const uploadUrl = "http://test.ntwrk.waits.io/upload"
type ProgressReader struct {
io.Reader
Reporter func(r int64) bool
Final bool
}
func (pr *ProgressReader) Read(p []byte) (n int, err error) {
if pr.Final {
return 0, errors.New("EOF")
} else {
n, err = pr.Reader.Read(p)
pr.Final = pr.Reporter(int64(n))
return n, err
}
}
func runTests() {
fmt.Print(HIDE)
db, ub := download(), upload()
fmt.Print(SHOW)
fmt.Printf("\n\nYour download speed is %.2f Mbps.\n", db)
fmt.Printf("Your upload speed is %.2f Mbps.\n", ub)
}
func printProgress(progress int8, bandwidth float64) {
fmt.Print(" ")
fmt.Printf("\r%3d%% @ %5.2f Mbps", progress, bandwidth)
}
func download() float64 {
fmt.Println("Testing download speed...")
resp, err := http.Get(downloadUrl)
check(err)
defer resp.Body.Close()
buf := make([]byte, 32768)
total := 0
start := time.Now()
var bandwidth, elapsed float64
for elapsed < 8 {
n, err := resp.Body.Read(buf)
check(err)
total += n
elapsed = time.Since(start).Seconds()
progress := int8(elapsed / 8 * 100)
bandwidth = float64(total) / elapsed / 128000
printProgress(progress, bandwidth)
}
return bandwidth
}
func upload() float64 {
fmt.Println("\nTesting upload speed...")
buf := bytes.NewBufferString(strings.Repeat("0123456789012345", 1000000))
total := int64(0)
start := time.Now()
var bandwidth float64
pr := &ProgressReader{buf, func(r int64) bool {
elapsed := time.Since(start).Seconds()
total += r
bandwidth = float64(total) / elapsed / 128000
printProgress(int8(elapsed/8*100), bandwidth)
if elapsed >= 8 {
return true
} else {
return false
}
}, false}
req, err := http.NewRequest("POST", uploadUrl, pr)
check(err)
http.DefaultClient.Do(req)
return bandwidth
}