forked from tokio-rs/axum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
70 lines (57 loc) · 1.71 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-rest-grpc-multiplex
//! ```
use self::multiplex_service::MultiplexService;
use axum::{routing::get, Router};
use proto::{
greeter_server::{Greeter, GreeterServer},
HelloReply, HelloRequest,
};
use std::net::SocketAddr;
use tonic::{Response as TonicResponse, Status};
mod multiplex_service;
mod proto {
tonic::include_proto!("helloworld");
}
#[derive(Default)]
struct GrpcServiceImpl {}
#[tonic::async_trait]
impl Greeter for GrpcServiceImpl {
async fn say_hello(
&self,
request: tonic::Request<HelloRequest>,
) -> Result<TonicResponse<HelloReply>, Status> {
tracing::info!("Got a request from {:?}", request.remote_addr());
let reply = HelloReply {
message: format!("Hello {}!", request.into_inner().name),
};
Ok(TonicResponse::new(reply))
}
}
async fn web_root() -> &'static str {
"Hello, World!"
}
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_rest_grpc_multiplex=debug".into()),
)
.init();
// build the rest service
let rest = Router::new().route("/", get(web_root));
// build the grpc service
let grpc = GreeterServer::new(GrpcServiceImpl::default());
// combine them into one service
let service = MultiplexService::new(rest, grpc);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(tower::make::Shared::new(service))
.await
.unwrap();
}