diff --git a/examples/src/interceptor/client.rs b/examples/src/interceptor/client.rs index f34cf66..6ef183b 100644 --- a/examples/src/interceptor/client.rs +++ b/examples/src/interceptor/client.rs @@ -1,6 +1,11 @@ use hello_world::greeter_client::GreeterClient; use hello_world::HelloRequest; -use tonic::{transport::Endpoint, Request, Status}; +use tonic::{ + codegen::InterceptedService, + service::Interceptor, + transport::{Channel, Endpoint}, + Request, Status, +}; pub mod hello_world { tonic::include_proto!("helloworld"); @@ -32,3 +37,40 @@ fn intercept(req: Request<()>) -> Result, Status> { println!("Intercepting request: {:?}", req); Ok(req) } + +// You can also use the `Interceptor` trait to create an interceptor type +// that is easy to name +struct MyInterceptor; + +impl Interceptor for MyInterceptor { + fn call(&mut self, request: tonic::Request<()>) -> Result, Status> { + Ok(request) + } +} + +#[allow(dead_code, unused_variables)] +async fn using_named_interceptor() -> Result<(), Box> { + let channel = Endpoint::from_static("http://[::1]:50051") + .connect() + .await?; + + let client: GreeterClient> = + GreeterClient::with_interceptor(channel, MyInterceptor); + + Ok(()) +} + +// Using a function pointer type might also be possible if your interceptor is a +// bare function that doesn't capture any variables +#[allow(dead_code, unused_variables, clippy::type_complexity)] +async fn using_function_pointer_interceptro() -> Result<(), Box> { + let channel = Endpoint::from_static("http://[::1]:50051") + .connect() + .await?; + + let client: GreeterClient< + InterceptedService) -> Result, Status>>, + > = GreeterClient::with_interceptor(channel, intercept); + + Ok(()) +} diff --git a/examples/src/interceptor/server.rs b/examples/src/interceptor/server.rs index a79d98e..263348a 100644 --- a/examples/src/interceptor/server.rs +++ b/examples/src/interceptor/server.rs @@ -31,6 +31,9 @@ async fn main() -> Result<(), Box> { let addr = "[::1]:50051".parse().unwrap(); let greeter = MyGreeter::default(); + // See examples/src/interceptor/client.rs for an example of how to create a + // named interceptor that can be returned from functions or stored in + // structs. let svc = GreeterServer::with_interceptor(greeter, intercept); println!("GreeterServer listening on {}", addr);