-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
67 lines (56 loc) · 1.41 KB
/
client.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
package main
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptrace"
"strings"
"time"
)
var client = http.Client{
Timeout: 10 * time.Second,
}
var startTime time.Time
var requestInterval = 1 * time.Second
func run(ctx context.Context, responsesCh chan Response) {
startTime = time.Now()
for {
select {
case <-ctx.Done():
return
default:
request, err := http.NewRequest(method, requestUrl, strings.NewReader(""))
if err != nil {
fmt.Println("could not create request", err)
return
}
var startT time.Time // represents when a successful connection is obtained
var endT time.Time // represents when the first byte of the response headers is available.
trace := &httptrace.ClientTrace{
// API also provides `ConnectDone`
GotConn: func(_ httptrace.GotConnInfo) { startT = time.Now() },
GotFirstResponseByte: func() { endT = time.Now() },
}
request = request.WithContext(httptrace.WithClientTrace(ctx, trace))
resp, err := client.Do(request)
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
fmt.Println("err sending request", err)
continue
}
code := resp.StatusCode
serverProcessingTime := endT.Sub(startT)
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
responsesCh <- Response{
StatusCode: code,
ResponseTime: serverProcessingTime,
}
time.Sleep(requestInterval)
}
}
}