5 unstable releases

0.2.0 Feb 10, 2024
0.1.0 Jan 13, 2023
0.0.3 Aug 31, 2022
0.0.2 Jun 18, 2022
0.0.1 Jun 18, 2022

#1118 in Web programming

Download history 3/week @ 2024-01-05 125/week @ 2024-01-12 33/week @ 2024-01-19 79/week @ 2024-01-26 150/week @ 2024-02-02 22/week @ 2024-02-09 59/week @ 2024-02-16 82/week @ 2024-02-23 33/week @ 2024-03-01 186/week @ 2024-03-08 106/week @ 2024-03-15 18/week @ 2024-03-22 50/week @ 2024-03-29 64/week @ 2024-04-05

359 downloads per month

MIT/Apache

17KB
197 lines

axum_tonic

Crates.io Documentation

A tiny crate to use Tonic with Axum.

This crate makes it simple to use different kinds of middleware with different tonic-services.

The recommended way to use this is to create two separate root-routers, one for grpc and one for rest. Then both can be combined together at the root, and turned into a make service.

See the docs of Axum or Tonic for more information about the respective frameworks.

Example


/// A middleware that does nothing, but just passes on the request.
async fn do_nothing_middleware<B>(req: Request<B>, next: Next<B>) -> Result<Response, GrpcStatus> {
    Ok(next.run(req).await)
}

/// A middleware that cancels the request with a grpc status-code
async fn cancel_request_middleware<B>(_req: Request<B>, _next: Next<B>) -> Result<Response, GrpcStatus> {
    Err(tonic::Status::cancelled("Canceled").into())
}

#[tokio::main]
async fn main() {

    // Spawn the Server
    tokio::task::spawn(async move {
        // The first grpc-service has middleware that accepts the request.
        let grpc_router1 = Router::new()
            .nest_tonic(Test1Server::new(Test1Service))
            .layer(from_fn(do_nothing_middleware));

        // The second grpc-service instead cancels the request
        let grpc_router2 = Router::new()
            .nest_tonic(Test2Server::new(Test2Service))
            .layer(from_fn(cancel_request_middleware));

        // Merge both routers into one.
        let grpc_router = grpc_router1.merge(grpc_router2);

        // This is the normal rest-router, to which all normal requests are routed
        let rest_router = Router::new()
            .nest("/", Router::new().route("/123", get(|| async move {})))
            .route("/", get(|| async move {}));

        // Combine both services into one
        let service = RestGrpcService::new(rest_router, grpc_router);

        // And serve at 127.0.0.1:8080
        axum::Server::bind(&"127.0.0.1:8080".parse().unwrap())
            .serve(service.into_make_service())
            .await
            .unwrap();
    });

    tokio::time::sleep(Duration::from_millis(100)).await;

    // Connect to the server with a grpc-client
    let channel = Channel::from_static("http://127.0.0.1:8080")
        .connect()
        .await
        .unwrap();

    let mut client1 = Test1Client::new(channel.clone());
    let mut client2 = Test2Client::new(channel);

    // The first request will succeed
    client1.test1(Test1Request {}).await.unwrap();

    // While the second one gives a grpc Status::Canceled code.
    assert_eq!(
        client2.test2(Test2Request {}).await.unwrap_err().code(),
        tonic::Code::Cancelled,
    );
}

Dependencies

~7–9MB
~164K SLoC