timer.go 661 B

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