context 提供連線中斷的機制,其中 WithTimeout 可以設定 timeout。
如果共用 context 會導致 timeout 的時間被佔用而提早結束連線。
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
start := time.Now()
for i := 0; i < 2; i++ {
if err := task(ctx); err != nil {
fmt.Println("(", time.Since(start), ")", err)
} else {
fmt.Println("(", time.Since(start), ")", "No error")
}
}
}
func task(ctx context.Context) error {
ticker := time.NewTimer(3 * time.Second)
select {
case <-ticker.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
output
( 3s ) No error
( 5s ) context deadline exceeded
上方程式碼設定 context timeout 為 5s, function task 每次會消耗 3s
由於共用 ctx,所以第一次沒有錯誤,第二次 5s 時觸發 timeout
每次連線時最好建立新的 context
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up