使用上下文取消工作

將具有超時(或使用取消功能)的上下文傳遞給長時間執行的函式可用於取消該函式的工作:

ctx, _ := context.WithTimeout(context.Background(), 200*time.Millisecond)
for {
    select {
    case <-ctx.Done():
        return ctx.Err()
    default:
        // Do an iteration of some long running work here!
    }
}