29 lines
684 B
Go
29 lines
684 B
Go
package middleware
|
|
|
|
import (
|
|
ers "code.30cm.net/wanderland/library-go/errors"
|
|
"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)
|
|
}
|