packages/tool/ctx.go
2025-06-13 16:10:20 +08:00

45 lines
873 B
Go

package tool
import (
"context"
"fmt"
"gitea.loveuer.com/yizhisec/packages/opt"
"time"
)
func Timeout(seconds ...int) (ctx context.Context) {
var (
duration time.Duration
)
if len(seconds) > 0 && seconds[0] > 0 {
duration = time.Duration(seconds[0]) * time.Second
} else {
duration = time.Duration(30) * time.Second
}
ctx, _ = context.WithTimeout(context.Background(), duration)
return
}
func CtxTimeout(ctx context.Context, seconds ...int) context.Context {
var (
duration time.Duration
)
if len(seconds) > 0 && seconds[0] > 0 {
duration = time.Duration(seconds[0]) * time.Second
} else {
duration = time.Duration(30) * time.Second
}
nctx, _ := context.WithTimeout(ctx, duration)
return nctx
}
func CtxTrace(ctx context.Context, key string) context.Context {
return context.WithValue(ctx, opt.TraceKey, fmt.Sprintf("%36s", key))
}