timeoutinterceptor.go 586 B

123456789101112131415161718192021222324
  1. package clientinterceptors
  2. import (
  3. "context"
  4. "time"
  5. "github.com/tal-tech/go-zero/core/contextx"
  6. "google.golang.org/grpc"
  7. )
  8. const defaultTimeout = time.Second * 2
  9. func TimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor {
  10. if timeout <= 0 {
  11. timeout = defaultTimeout
  12. }
  13. return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
  14. invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  15. ctx, cancel := contextx.ShrinkDeadline(ctx, timeout)
  16. defer cancel()
  17. return invoker(ctx, method, req, reply, cc, opts...)
  18. }
  19. }