timeoutinterceptor.go 577 B

12345678910111213141516171819202122
  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. func TimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor {
  9. return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
  10. invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  11. if timeout <= 0 {
  12. return invoker(ctx, method, req, reply, cc, opts...)
  13. }
  14. ctx, cancel := contextx.ShrinkDeadline(ctx, timeout)
  15. defer cancel()
  16. return invoker(ctx, method, req, reply, cc, opts...)
  17. }
  18. }