deadline.go 472 B

12345678910111213141516171819
  1. package contextx
  2. import (
  3. "context"
  4. "time"
  5. )
  6. // ShrinkDeadline returns a new Context with proper deadline base on the given ctx and timeout.
  7. // And returns a cancel function as well.
  8. func ShrinkDeadline(ctx context.Context, timeout time.Duration) (context.Context, func()) {
  9. if deadline, ok := ctx.Deadline(); ok {
  10. leftTime := time.Until(deadline)
  11. if leftTime < timeout {
  12. timeout = leftTime
  13. }
  14. }
  15. return context.WithDeadline(ctx, time.Now().Add(timeout))
  16. }