-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestor.go
92 lines (84 loc) · 1.72 KB
/
requestor.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 decorator
import (
"io"
"io/ioutil"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
type response struct {
duration time.Duration
err error
}
type Job struct {
Client Client
NumRequests int
Request *http.Request
IntervalSecs int
responseChan chan *response
}
func (b *Job) displayProgress(stopChan chan struct{}) {
var prevResponseCount int
for {
select {
case <-time.Tick(time.Millisecond * 500):
responseCount := len(b.responseChan)
if prevResponseCount < responseCount {
prevResponseCount = responseCount
Debug.Printf("> %d requests done.", responseCount)
}
case <-stopChan:
return
}
}
}
func (j *Job) Run() {
j.responseChan = make(chan *response, j.NumRequests)
stopChan := make(chan struct{})
go j.displayProgress(stopChan)
interruptChan := make(chan os.Signal, 1)
signal.Notify(interruptChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-interruptChan
stopChan <- struct{}{}
close(j.responseChan)
os.Exit(130)
}()
var wg sync.WaitGroup
intervalSecs := time.Duration(j.IntervalSecs)
requestsPerformed := 0
for range time.Tick(intervalSecs * time.Second) {
wg.Add(1)
go func() {
client := j.Client
j.makeRequest(client)
wg.Done()
}()
requestsPerformed++
if requestsPerformed >= j.NumRequests {
break
}
}
wg.Wait()
stopChan <- struct{}{}
Debug.Printf("All requests done.")
close(j.responseChan)
}
func (j *Job) makeRequest(c Client) {
Debug.Printf("makeRequest: ")
start := time.Now()
resp, err := c.Do(j.Request)
if err == nil {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
t := time.Now()
finish := t.Sub(start)
j.responseChan <- &response{
duration: finish,
err: err,
}
}