deadline.go 334 B

1234567891011121314151617
  1. package contextx
  2. import (
  3. "context"
  4. "time"
  5. )
  6. func ShrinkDeadline(ctx context.Context, timeout time.Duration) (context.Context, func()) {
  7. if deadline, ok := ctx.Deadline(); ok {
  8. leftTime := time.Until(deadline)
  9. if leftTime < timeout {
  10. timeout = leftTime
  11. }
  12. }
  13. return context.WithDeadline(ctx, time.Now().Add(timeout))
  14. }