2024-08-12 14:20:13 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2024-08-15 08:17:41 +00:00
|
|
|
ers "code.30cm.net/wanderland/library-go/errors"
|
2024-08-12 14:20:13 +00:00
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
)
|
|
|
|
|
|
|
|
const defaultTimeout = 30 * time.Second
|
|
|
|
|
|
|
|
func TimeoutMiddleware(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
|
|
|
|
|
|
|
|
newCtx, cancelCtx := context.WithTimeout(ctx, defaultTimeout)
|
|
|
|
defer func() {
|
|
|
|
cancelCtx()
|
|
|
|
|
|
|
|
if errors.Is(newCtx.Err(), context.DeadlineExceeded) {
|
|
|
|
err = ers.SystemTimeoutError(info.FullMethod)
|
|
|
|
logx.Errorf("Method: %s, request %v, timeout: %d", info.FullMethod, req, defaultTimeout)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|