从 Go 的上下文中获取超时值



如何获取上下文中为超时设置的持续时间。

示例:

func f(ctx context.Context) {
// get ctx timeout value
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(),2*time.Second)
defer cancel()
f(ctx)
}

如何从函数f中获取持续时间2*time.Second

如果函数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)
}

https://play.golang.org/p/n3lZJAMdLYs

最新更新