Skip to content

Commit

Permalink
doc(tonic): add more interceptor examples (hyperium#736)
Browse files Browse the repository at this point in the history
Some have asked how to use the new `Interceptor` trait to create named
interceptors. This updates the client example to show how to do that.
  • Loading branch information
davidpdrsn authored Aug 9, 2021
1 parent 8c8f4d1 commit 4e578b5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
44 changes: 43 additions & 1 deletion examples/src/interceptor/client.rs
Original file line number Diff line number Diff line change
@@ -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");
Expand Down Expand Up @@ -32,3 +37,40 @@ fn intercept(req: Request<()>) -> Result<Request<()>, 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<tonic::Request<()>, Status> {
Ok(request)
}
}

#[allow(dead_code, unused_variables)]
async fn using_named_interceptor() -> Result<(), Box<dyn std::error::Error>> {
let channel = Endpoint::from_static("https://[::1]:50051")
.connect()
.await?;

let client: GreeterClient<InterceptedService<Channel, MyInterceptor>> =
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<dyn std::error::Error>> {
let channel = Endpoint::from_static("https://[::1]:50051")
.connect()
.await?;

let client: GreeterClient<
InterceptedService<Channel, fn(tonic::Request<()>) -> Result<tonic::Request<()>, Status>>,
> = GreeterClient::with_interceptor(channel, intercept);

Ok(())
}
3 changes: 3 additions & 0 deletions examples/src/interceptor/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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);
Expand Down

0 comments on commit 4e578b5

Please sign in to comment.