feat: Add gRPC interceptors (#232)
This change introduces proper gRPC interceptors that are avilable regardless of the transport used. Each codegen service now produces an additional method called `with_interceptor` that accepts a `Interceptor`. All examples have been updated to use this new style and interop has a custom `tower::Service` middleware to echo the headers. There is also a new `interceptor` example that shows basic usage. BREAKING CHANGE: removed `interceptor_fn` and `intercep_headers_fn` from `transport` in favor of using `tonic::Interceptor`.
This commit is contained in:
@@ -1,10 +1,7 @@
|
||||
use http::header::HeaderName;
|
||||
use structopt::StructOpt;
|
||||
use tonic::body::BoxBody;
|
||||
use tonic::client::GrpcService;
|
||||
use tonic::transport::Server;
|
||||
use tonic::transport::{Identity, ServerTlsConfig};
|
||||
use tonic_interop::{server, MergeTrailers};
|
||||
use tonic_interop::server;
|
||||
|
||||
#[derive(StructOpt)]
|
||||
struct Opts {
|
||||
@@ -20,33 +17,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let addr = "127.0.0.1:10000".parse().unwrap();
|
||||
|
||||
let mut builder = Server::builder().interceptor_fn(|svc, req| {
|
||||
let echo_header = req
|
||||
.headers()
|
||||
.get("x-grpc-test-echo-initial")
|
||||
.map(Clone::clone);
|
||||
|
||||
let echo_trailer = req
|
||||
.headers()
|
||||
.get("x-grpc-test-echo-trailing-bin")
|
||||
.map(Clone::clone)
|
||||
.map(|v| (HeaderName::from_static("x-grpc-test-echo-trailing-bin"), v));
|
||||
|
||||
let call = svc.call(req);
|
||||
|
||||
async move {
|
||||
let mut res = call.await?;
|
||||
|
||||
if let Some(echo_header) = echo_header {
|
||||
res.headers_mut()
|
||||
.insert("x-grpc-test-echo-initial", echo_header);
|
||||
}
|
||||
|
||||
Ok(res
|
||||
.map(|b| MergeTrailers::new(b, echo_trailer))
|
||||
.map(BoxBody::new))
|
||||
}
|
||||
});
|
||||
let mut builder = Server::builder();
|
||||
|
||||
if matches.use_tls {
|
||||
let cert = tokio::fs::read("interop/data/server1.pem").await?;
|
||||
@@ -60,8 +31,11 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let unimplemented_service =
|
||||
server::UnimplementedServiceServer::new(server::UnimplementedService::default());
|
||||
|
||||
// Wrap this test_service with a service that will echo headers as trailers.
|
||||
let test_service_svc = server::EchoHeadersSvc::new(test_service);
|
||||
|
||||
builder
|
||||
.add_service(test_service)
|
||||
.add_service(test_service_svc)
|
||||
.add_service(unimplemented_service)
|
||||
.serve(addr)
|
||||
.await?;
|
||||
|
||||
Reference in New Issue
Block a user