返回一个timerCtx示例,设置具体的deadline时间,到达 deadline的时候,后代goroutine退出。
WithTimeout
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return WithDeadline(parent, time.Now().Add(timeout))
}
和WithDeadline一样返回一个timerCtx示例,实际上就是WithDeadline包了一层,直接传入时间的持续时间,结束后退出。
WithValue
func WithValue(parent Context, key, val interface{}) Context {
if key == nil {
panic("nil key")
}
if !reflect.TypeOf(key).Comparable() {
panic("key is not comparable")
}
return &valueCtx{parent, key, val}
}
WithValue对应valueCtx ,WithValue是在Context中设置一个 map,这个Context以及它的后代的goroutine都可以拿到map 里的值。
例子
Context的使用最多的地方就是在Golang的web开发中,在http包的Server中,每一个请求在都有一个对应的goroutine去处理。请求处理函数通常会启动额外的goroutine用来访问后端服务,比如数据库和RPC服务。用来处理一个请求的goroutine通常需要访问一些与请求特定的数据,比如终端用户的身份认证信息、验证相关的token、请求的截止时间。 当一个请求被取消或超时时,所有用来处理该请求的 goroutine都应该迅速退出,然后系统才能释放这些goroutine占用的资源。虽然我们不能从外部杀死某个goroutine,所以我就得让它自己结束,之前我们用channel+select的方式,来解决这个问题,但是有些场景实现起来比较麻烦,例如由一个请求衍生出的各个 goroutine之间需要满足一定的约束关系,以实现一些诸如有效期,中止goroutine树,传递请求全局变量之类的功能。
保存上下文
func middleWare(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := context.WithValue(req.Context(),"key","value")
next.ServeHTTP(w, req.WithContext(ctx))
})
}
func handler(w http.ResponseWriter, req *http.Request) {
value := req.Context().Value("value").(string)
fmt.Fprintln(w, "value: ", value)
return
}
func main() {
http.Handle("/", middleWare(http.HandlerFunc(handler)))
http.ListenAndServe(":8080", nil)
}
我们可以在上下文中保存任何的类型的数据,用于在整个请求的生命周期去传递使用。
超时控制
func longRunningCalculation(timeCost int)chan string{
result:=make(chan string)
go func (){
time.Sleep(time.Second*(time.Duration(timeCost)))
result<-"Done"
}()
return result
}
func jobWithTimeoutHandler(w http.ResponseWriter, r * http.Request){
ctx,cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
select{
case <-ctx.Done():
log.Println(ctx.Err())
return
case result:=<-longRunningCalculation(5):
io.WriteString(w,result)
}
return
}
func main() {
http.Handle("/", jobWithTimeoutHandler)
http.ListenAndServe(":8080", nil)
}









