package helper import ( "context" "time" ) // valueOnlyContext 包装一个只有value的context type valueOnlyContext struct{ context.Context } func (valueOnlyContext) Deadline() (deadline time.Time, ok bool) { return } func (valueOnlyContext) Done() <-chan struct{} { return nil } func (valueOnlyContext) Err() error { return nil } // CopyValueCtx 复制一个只有value的context func CopyValueCtx(ctx context.Context) context.Context { return valueOnlyContext{ctx} } // RunTaskWithTimeout 带有超时控制的任务执行函数 func RunTaskWithTimeout(ctx context.Context, task func(ctx context.Context) error, timeout time.Duration) error { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() done := make(chan error, 1) go func() { done <- task(ctx) }() select { case err := <-done: return err case <-ctx.Done(): return ctx.Err() } }