如何获取上下文中超时设置的持续时间。
例子:
func f(ctx context.Context) {
// get ctx timeout value
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(),2*time.Second)
defer cancel()
f(ctx)
}
Run Code Online (Sandbox Code Playgroud)
如何2*time.Second从函数内获取持续时间f?
如果 func f 立即被调用,那么直到超时的时间就是刚刚设置的时间,因此您可以通过查看截止时间来获取它
package main
import (
"context"
"fmt"
"time"
)
func f(ctx context.Context) {
deadline,_:=ctx.Deadline()
fmt.Println(time.Until(deadline))
// get ctx timeout value
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
f(ctx)
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/n3lZJAMdLYs