timer.go 808 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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 ctx.Err() != context.DeadlineExceeded {
  19. panic(newError(499, fmt.Sprintf("Request was cancelled after %v", d), "Cancelled"))
  20. }
  21. if newRelicEnabled {
  22. sendTimeoutToNewRelic(ctx, d)
  23. }
  24. if prometheusEnabled {
  25. incrementPrometheusErrorsTotal("timeout")
  26. }
  27. panic(newError(503, fmt.Sprintf("Timeout after %v", d), "Timeout"))
  28. default:
  29. // Go ahead
  30. }
  31. }