timer.go 589 B

1234567891011121314151617181920212223242526272829
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. var timerSinceCtxKey = ctxKey("timerSince")
  8. func startTimer(d time.Duration) (context.Context, context.CancelFunc) {
  9. return context.WithTimeout(
  10. context.WithValue(context.Background(), timerSinceCtxKey, time.Now()),
  11. d,
  12. )
  13. }
  14. func getTimerSince(ctx context.Context) time.Duration {
  15. return time.Since(ctx.Value(timerSinceCtxKey).(time.Time))
  16. }
  17. func checkTimeout(ctx context.Context) {
  18. select {
  19. case <-ctx.Done():
  20. panic(newError(503, fmt.Sprintf("Timeout after %v", getTimerSince(ctx)), "Timeout"))
  21. default:
  22. // Go ahead
  23. }
  24. }