app-cloudep-member-server/internal/lib/middleware/with_context.go

29 lines
681 B
Go

package middleware
import (
"context"
"errors"
"time"
ers "code.30cm.net/digimon/library-go/errors"
"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)
}