-
Notifications
You must be signed in to change notification settings - Fork 1k
/
server.rs
40 lines (30 loc) · 1.16 KB
/
server.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
pub mod pb {
tonic::include_proto!("grpc.examples.unaryecho");
}
use pb::{EchoRequest, EchoResponse};
use tonic::{metadata::MetadataValue, transport::Server, Request, Response, Status};
type EchoResult<T> = Result<Response<T>, Status>;
#[derive(Default)]
pub struct EchoServer {}
#[tonic::async_trait]
impl pb::echo_server::Echo for EchoServer {
async fn unary_echo(&self, request: Request<EchoRequest>) -> EchoResult<EchoResponse> {
let message = request.into_inner().message;
Ok(Response::new(EchoResponse { message }))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse().unwrap();
let server = EchoServer::default();
let svc = pb::echo_server::EchoServer::with_interceptor(server, check_auth);
Server::builder().add_service(svc).serve(addr).await?;
Ok(())
}
fn check_auth(req: Request<()>) -> Result<Request<()>, Status> {
let token: MetadataValue<_> = "Bearer some-secret-token".parse().unwrap();
match req.metadata().get("authorization") {
Some(t) if token == t => Ok(req),
_ => Err(Status::unauthenticated("No valid auth token")),
}
}