go-zero/rpcx/internal/clientinterceptors/timeoutinterceptor.go

25 lines
586 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package clientinterceptors
import (
"context"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/contextx"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
)
const defaultTimeout = time.Second * 2
func TimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor {
if timeout <= 0 {
timeout = defaultTimeout
}
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
ctx, cancel := contextx.ShrinkDeadline(ctx, timeout)
defer cancel()
return invoker(ctx, method, req, reply, cc, opts...)
}
}