feat: 添加 MustStop 方法

feat: 添加 gin 统一执行 api 函数
This commit is contained in:
zhaoyupeng
2025-07-10 16:16:52 +08:00
parent 6cd0fa3d6c
commit 7f49105b23
2 changed files with 95 additions and 0 deletions

View File

@ -1,7 +1,9 @@
package tool
import (
"context"
"gitea.loveuer.com/yizhisec/packages/logger"
"sync"
)
func Must(errs ...error) {
@ -16,3 +18,36 @@ func MustWithData[T any](data T, err error) T {
Must(err)
return data
}
func MustStop(ctx context.Context, stopFns ...func(ctx context.Context) error) {
if len(stopFns) == 0 {
return
}
ok := make(chan struct{})
wg := &sync.WaitGroup{}
wg.Add(len(stopFns))
for _, fn := range stopFns {
go func() {
defer wg.Done()
if err := fn(ctx); err != nil {
logger.ErrorCtx(ctx, "stop function failed, err = %s", err.Error())
}
}()
}
go func() {
select {
case <-ctx.Done():
logger.FatalCtx(ctx, "stop function timeout, force down")
case _, _ = <-ok:
return
}
}()
wg.Wait()
close(ok)
}