-
Notifications
You must be signed in to change notification settings - Fork 6
/
latency.go
26 lines (23 loc) · 843 Bytes
/
latency.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
package mem
import (
"context"
"time"
)
// handleWithLatency allows introduction of artificial latency while handling context cancellation.
// The method first wait for the given latency while monitoring ctx.Done. If context is canceled
// during the wait, the context error is returned.
// If latency passed, the handler is executed and it's error output is returned.
func handleWithLatency(latency time.Duration, ctx context.Context, handler func() error) error {
if latency == 0 {
return handler()
}
select {
case <-ctx.Done():
// Monitor context cancellation. cancellation may happend if the client closed the connection
// or if the configured request timeout has been reached.
return ctx.Err()
case <-time.After(latency):
// Wait for the given latency before the execute the provided handler.
return handler()
}
}