Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How does tonic library dynamically set up custom middleware #1800

Open
tgy3300 opened this issue Jul 15, 2024 · 1 comment
Open

How does tonic library dynamically set up custom middleware #1800

tgy3300 opened this issue Jul 15, 2024 · 1 comment

Comments

@tgy3300
Copy link

tgy3300 commented Jul 15, 2024

pub struct GrpcStruct <F> 
where
    F: tonic::service::interceptor::Interceptor + Clone + Send + Sync + 'static,
{
    middleware: Vec<F>,
}

Setting the layer manually is fine

        let ss = self.middleware[0].clone();
        let ss1 = self.middleware[1].clone();
        let ss2 = self.middleware[2].clone();

        tonic::transport::Server::builder()
            .layer(interceptor(ss))
            .layer(interceptor(ss1))
            .layer(interceptor(ss2))
            .add_service(srv)
            .serve(address)
            .await
            .unwrap();

// But change to dynamic add, will report an error, the error at the bottom

        let mut app = tonic::transport::Server::builder();
        for mid in self.middleware.iter() {
            app = app.layer(interceptor(mid.clone()));
        }
        app.add_service(srv).serve(address).await.unwrap();

Report an error:
image

@alexrudy
Copy link
Contributor

Middleware in tower is statically typed - so you can't add to it dynamically like this. You might be able to use a lot of boxed services to get around this. See BoxLayer for some inspiration and a better explanation of why this won't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants