guard/internal/lib/middleware/with_context.go

29 lines
675 B
Go
Raw Normal View History

2024-08-06 05:59:24 +00:00
package middleware
import (
ers "ark-permission/internal/lib/error"
"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)
}