作者回复: context就是用于管理相关任务的上下文,包含了共享值的传递,超时,取消通知
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
Deadline会返回一个超时时间,Goroutine获得了超时时间后,例如可以对某些io操作设定超时时间。
Done方法返回一个信道(channel),当Context被撤销或过期时,该信道是关闭的,即它是一个表示Context是否已关闭的信号。
当Done信道关闭后,Err方法表明Context被撤的原因。
Value可以让Goroutine共享一些数据,当然获得数据是协程安全的。但使用这些数据的时候要注意同步,比如返回了一个map,而这个map的读写则要加
作者回复: 这个cancel就是由相关的context生成的。参考下面的实例代码:
package cancel_with_ctx
import (
"fmt"
"testing"
)
func WithContext(ctx int) (Cancel func()) {
return func() {
fmt.Println("The value of ctx is ", ctx)
}
}
func TestWithContext(t *testing.T) {
cancel := WithContext(10)
cancel()
//output: The value of ctx is 10
}
作者回复: 推荐你一个,简单的
https://github.com/easierway/service_decorators/blob/master/README.md