You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
20 lines
472 B
Go
20 lines
472 B
Go
package contextx
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
)
|
|
|
|
// ShrinkDeadline returns a new Context with proper deadline base on the given ctx and timeout.
|
|
// And returns a cancel function as well.
|
|
func ShrinkDeadline(ctx context.Context, timeout time.Duration) (context.Context, func()) {
|
|
if deadline, ok := ctx.Deadline(); ok {
|
|
leftTime := time.Until(deadline)
|
|
if leftTime < timeout {
|
|
timeout = leftTime
|
|
}
|
|
}
|
|
|
|
return context.WithDeadline(ctx, time.Now().Add(timeout))
|
|
}
|