2017-10-04 21:44:58 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2018-10-05 17:17:36 +02:00
|
|
|
"context"
|
2017-10-04 21:44:58 +02:00
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2018-10-05 17:17:36 +02:00
|
|
|
var timerSinceCtxKey = ctxKey("timerSince")
|
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
type timer struct {
|
|
|
|
StartTime time.Time
|
|
|
|
Timer <-chan time.Time
|
|
|
|
}
|
|
|
|
|
2018-10-05 17:17:36 +02:00
|
|
|
func startTimer(d time.Duration) (context.Context, context.CancelFunc) {
|
|
|
|
return context.WithTimeout(
|
|
|
|
context.WithValue(context.Background(), timerSinceCtxKey, time.Now()),
|
|
|
|
d,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
func getTimerSince(ctx context.Context) time.Duration {
|
|
|
|
return time.Since(ctx.Value(timerSinceCtxKey).(time.Time))
|
2017-10-04 21:44:58 +02:00
|
|
|
}
|
|
|
|
|
2018-10-05 17:17:36 +02:00
|
|
|
func checkTimeout(ctx context.Context) {
|
2017-10-04 21:44:58 +02:00
|
|
|
select {
|
2018-10-05 17:17:36 +02:00
|
|
|
case <-ctx.Done():
|
|
|
|
panic(newError(503, fmt.Sprintf("Timeout after %v", getTimerSince(ctx)), "Timeout"))
|
2017-10-04 21:44:58 +02:00
|
|
|
default:
|
|
|
|
// Go ahead
|
|
|
|
}
|
|
|
|
}
|