Last active
October 1, 2024 13:58
-
-
Save afpro/149c598ade2ad7f2466e0e0c40a55f19 to your computer and use it in GitHub Desktop.
serve tonic service on axum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{convert::Infallible, error::Error}; | |
use axum::{ | |
body::Body, | |
http::{Request, Response}, | |
Router, | |
}; | |
use tonic::{body::BoxBody, server::NamedService}; | |
use tower::Service; | |
pub trait TonicAxum: Sized { | |
fn add_tonic_service<S>(self, service: S) -> Self | |
where | |
S: Service<Request<Body>, Response = Response<BoxBody>, Error = Infallible> | |
+ NamedService | |
+ Clone | |
+ Send | |
+ 'static, | |
S::Future: Send + 'static, | |
S::Error: Into<Box<dyn Error + Send + Sync>> + Send; | |
fn add_tonic_reflection( | |
self, | |
desc_list: &[&[u8]], | |
) -> Result<Self, tonic_reflection::server::Error> { | |
let mut service = tonic_reflection::server::Builder::configure(); | |
for desc in desc_list { | |
service = service.register_encoded_file_descriptor_set(desc); | |
} | |
let service = service.build_v1()?; | |
Ok(self.add_tonic_service(service)) | |
} | |
} | |
impl TonicAxum for Router { | |
fn add_tonic_service<S>(self, service: S) -> Self | |
where | |
S: Service<Request<Body>, Response = Response<BoxBody>, Error = Infallible> | |
+ NamedService | |
+ Clone | |
+ Send | |
+ 'static, | |
S::Future: Send + 'static, | |
S::Error: Into<Box<dyn Error + Send + Sync>> + Send, | |
{ | |
self.route_service(&format!("/{}/*rest", S::NAME), service) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment