2 回答

TA貢獻1802條經驗 獲得超4個贊
這取決于您的和方法的行為方式。讓我們想象一下,該方法是一個簡單的短命goroutine,它對DB進行一個查詢,您唯一想要的就是檢查其父上下文是否為“完成”或“取消”。然后,您可以為 Foo 方法提供父上下文。FooBarFoo
func main() {
uri := "mongodb://localhost:27017"
ctx := context.Background()
client, err := Connect(ctx, uri)
ctx, cancel := context.WithCancel(ctx)
if err != nil {
panic(err)
}
go Foo(ctx, client)
go Bar(context.WithValue(ctx, "uri", uri), client)
// cancel parent context
cancel()
time.Sleep(5*time.Second)
}
func Foo(ctx context.Context, client *Client) {
fmt.Printf("Foo: %s\n", ctx.Value("uri"))
select {
case <- ctx.Done():
err := ctx.Err()
if err != nil {
// you could switch for the actual reason
fmt.Println("In our case context canceled: ", err)
return
}
fmt.Printf("Do something...")
}
}
另一方面,如果執行一些重要的邏輯并對 DB 進行多次調用,您可能希望一個單獨的上下文能夠將其與父上下文分開取消。然后,您可以從父母那里獲得新的上下文。Bar
func Bar(ctx context.Context, client *Client) {
// Bar has a non trivial logic and needs a separate cancellation and handling
ctx, cancelFunc := context.WithCancel(ctx)
fmt.Printf("Bar: %s\n", ctx.Value("uri"))
// cancel derived context
cancelFunc()
}

TA貢獻1719條經驗 獲得超6個贊
我也這樣做過
type DB struct {
client *mongo.Client
}
func (db *DB) GetVideoStream {}
func main() {
ctx, _ := context.WithTimeout(context.Background(), 60*time.Second)
client, err := mongo.Connect(ctx, clientOpts)
db := &DB{client: client}
go db.GetVideoStream()
http.HandleFunc("/api/", db.GetVideoStream)
}
您可以使用指針接收器來執行相同的操作。
我是新來的,還是該語言的新手
- 2 回答
- 0 關注
- 136 瀏覽
添加回答
舉報