timeoutinterceptor.go 545 B

12345678910111213141516171819
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "time"
  5. "github.com/tal-tech/go-zero/core/contextx"
  6. "google.golang.org/grpc"
  7. )
  8. // UnaryTimeoutInterceptor returns a func that sets timeout to incoming unary requests.
  9. func UnaryTimeoutInterceptor(timeout time.Duration) grpc.UnaryServerInterceptor {
  10. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
  11. handler grpc.UnaryHandler) (resp interface{}, err error) {
  12. ctx, cancel := contextx.ShrinkDeadline(ctx, timeout)
  13. defer cancel()
  14. return handler(ctx, req)
  15. }
  16. }