-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdelayed.go
70 lines (59 loc) · 1.98 KB
/
delayed.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
package transport
import (
"fmt"
"math/rand"
"net/http"
"time"
)
// DelayedRequest is a middleware that delays requests, useful when testing
// timeouts while waiting on a request to be sent upstream.
func DelayedRequest(requestDelayMin, requestDelayMax time.Duration) func(http.RoundTripper) http.RoundTripper {
if requestDelayMin > requestDelayMax {
panic(fmt.Sprintf("requestDelayMin %v is greater than requestDelayMax %v", requestDelayMin, requestDelayMax))
}
return delayedRoundTripper(randDelay(requestDelayMin, requestDelayMax), 0)
}
// DelayedResponse is a middleware that delays responses, useful when testing
// timeouts after upstream has processed the request, the response is hold back
// until the delay is over.
func DelayedResponse(responseDelayMin, responseDelayMax time.Duration) func(http.RoundTripper) http.RoundTripper {
if responseDelayMin > responseDelayMax {
panic(fmt.Sprintf("responseDelayMin %v is greater than responseDelayMax %v", responseDelayMin, responseDelayMax))
}
return delayedRoundTripper(0, randDelay(responseDelayMin, responseDelayMax))
}
func delayedRoundTripper(requestDelay, responseDelay time.Duration) func(http.RoundTripper) http.RoundTripper {
return func(next http.RoundTripper) http.RoundTripper {
return RoundTripFunc(func(req *http.Request) (*http.Response, error) {
ctx := req.Context()
// wait before sending request
if requestDelay > 0 {
ticker := time.NewTicker(requestDelay)
defer ticker.Stop()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
}
}
res, err := next.RoundTrip(req)
// wait before sending response body
if responseDelay > 0 {
ticker := time.NewTicker(responseDelay)
defer ticker.Stop()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
}
}
return res, err
})
}
}
func randDelay(min, max time.Duration) time.Duration {
if min >= max {
return min
}
return min + time.Duration(rand.Int63n(int64(max-min)))
}