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

24 lines
592 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package clientinterceptors
import (
"context"
"time"
"google.golang.org/grpc"
)
2021-03-01 23:52:44 +08:00
// TimeoutInterceptor is an interceptor that controls timeout.
2020-07-26 17:09:05 +08:00
func TimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
if timeout <= 0 {
2021-02-19 10:24:03 +08:00
return invoker(ctx, method, req, reply, cc, opts...)
}
ctx, cancel := context.WithTimeout(ctx, timeout)
2020-07-26 17:09:05 +08:00
defer cancel()
2021-07-24 22:29:02 +08:00
return invoker(ctx, method, req, reply, cc, opts...)
2020-07-26 17:09:05 +08:00
}
}