timer.go 671 B

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