forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
40 lines (31 loc) · 808 Bytes
/
timer.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
package main
import (
"context"
"fmt"
"time"
)
var timerSinceCtxKey = ctxKey("timerSince")
func setTimerSince(ctx context.Context) context.Context {
return context.WithValue(ctx, timerSinceCtxKey, time.Now())
}
func getTimerSince(ctx context.Context) time.Duration {
return time.Since(ctx.Value(timerSinceCtxKey).(time.Time))
}
func checkTimeout(ctx context.Context) {
select {
case <-ctx.Done():
d := getTimerSince(ctx)
if ctx.Err() != context.DeadlineExceeded {
panic(newError(499, fmt.Sprintf("Request was cancelled after %v", d), "Cancelled"))
}
if newRelicEnabled {
sendTimeoutToNewRelic(ctx, d)
}
if prometheusEnabled {
incrementPrometheusErrorsTotal("timeout")
}
panic(newError(503, fmt.Sprintf("Timeout after %v", d), "Timeout"))
default:
// Go ahead
}
}