-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsloth.go
106 lines (93 loc) · 2.25 KB
/
sloth.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
package main
import (
"flag"
"fmt"
"net/http"
"os"
"sync"
"time"
"github.com/stonedem0/sloth/table"
"github.com/stonedem0/sloth/terminal"
"github.com/stonedem0/sloth/validator"
"github.com/logrusorgru/aurora"
"github.com/stonedem0/tofu"
)
const (
softPink = 213
purple = 57
)
func main() {
t := tofu.ProgressBarStr{}
count := flag.Int("count", 10, "number of requests")
flag.Parse()
urls := flag.Args()
argsWithoutProg := os.Args[1:]
if len(argsWithoutProg) == 0 {
slothMsg := "Hi. It's Sloth. Looks like you're trying to talk to me. Try some of these commands:\n"
commads := " • [urls]: list of URls for testing "
fmt.Printf("%s %s", aurora.Index(57, slothMsg), aurora.Index(201, commads))
os.Exit(1)
}
for _, u := range urls {
validator.URLValidator(u)
}
results := make(chan Result)
total := len(urls) * *count
m := map[string][]time.Duration{}
errors := map[string][]error{}
// Terminal setup
terminal.CleanTerminalScreen()
terminal.MoveCursorUpperLeft()
terminal.HideCursor()
go Sloth(urls, *count, results)
for a := 0; a < total; a++ {
r := <-results
m[r.URL] = append(m[r.URL], r.Duration)
if r.Error == nil {
t.ProgressBar(float32(a)/float32(total), 40, softPink, "▇", "░")
t.PrintProgressBar()
continue
}
errors[r.URL] = append(errors[r.URL], r.Error)
}
close(results)
terminal.EraseProgressBar()
terminal.MoveCursorUpperLeft()
table.PrintTable(m, *count)
for url, e := range errors {
for _, err := range e {
fmt.Printf("%s has an error:\n %s\n", aurora.Index(118, url), aurora.Index(197, err))
}
}
//Show cursor
terminal.ShowCursor()
}
// Result ...
type Result struct {
Error error
Index int
Duration time.Duration
URL string
}
// Sloth ...
func Sloth(urls []string, count int, res chan Result) {
var wg sync.WaitGroup
wg.Add(len(urls) * count)
for _, val := range urls {
for a := 0; a < count; a++ {
go func(val string, index int) {
defer wg.Done()
start := time.Now()
r, err := http.Get(val)
if err != nil {
res <- Result{Index: index, URL: val, Error: err}
return
}
defer r.Body.Close()
elapsed := time.Since(start).Round(time.Millisecond)
res <- Result{Index: index, Duration: elapsed, URL: val}
}(val, a)
}
}
wg.Wait()
}