使用上下文取消工作

将具有超时(或使用取消功能)的上下文传递给长时间运行的函数可用于取消该函数的工作:

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!
    }
}