Add tls example with rustls

This commit is contained in:
Lucio Franco
2019-09-29 19:45:05 -04:00
parent 2c2b7d7904
commit a8ef9d6c42
6 changed files with 185 additions and 1 deletions
+28
View File
@@ -0,0 +1,28 @@
pub mod pb {
include!(concat!(env!("OUT_DIR"), "/grpc.examples.echo.rs"));
}
use pb::{client::EchoClient, EchoRequest};
use tonic::transport::{Certificate, Channel};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let pem = tokio::fs::read("tonic-examples/data/tls/ca.pem").await?;
let ca = Certificate::from_pem(pem);
let channel = Channel::from_static("http://[::1]:50051")
.rustls_tls(ca, Some("example.com".into()))
.channel();
let mut client = EchoClient::new(channel);
let request = tonic::Request::new(EchoRequest {
message: "hello".into(),
});
let response = client.unary_echo(request).await?;
println!("RESPONSE={:?}", response);
Ok(())
}
+65
View File
@@ -0,0 +1,65 @@
pub mod pb {
include!(concat!(env!("OUT_DIR"), "/grpc.examples.echo.rs"));
}
use pb::{EchoRequest, EchoResponse};
use std::collections::VecDeque;
use tonic::{transport::{Server, Identity}, Request, Response, Status, Streaming};
type EchoResult<T> = Result<Response<T>, Status>;
type Stream = VecDeque<Result<EchoResponse, Status>>;
#[derive(Default)]
pub struct EchoServer;
#[tonic::async_trait]
impl pb::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 }))
}
type ServerStreamingEchoStream = Stream;
async fn server_streaming_echo(
&self,
_: Request<EchoRequest>,
) -> EchoResult<Self::ServerStreamingEchoStream> {
Err(Status::unimplemented("not implemented"))
}
async fn client_streaming_echo(
&self,
_: Request<Streaming<EchoRequest>>,
) -> EchoResult<EchoResponse> {
Err(Status::unimplemented("not implemented"))
}
type BidirectionalStreamingEchoStream = Stream;
async fn bidirectional_streaming_echo(
&self,
_: Request<Streaming<EchoRequest>>,
) -> EchoResult<Self::BidirectionalStreamingEchoStream> {
Err(Status::unimplemented("not implemented"))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cert = tokio::fs::read("tonic-examples/data/tls/server.pem").await?;
let key = tokio::fs::read("tonic-examples/data/tls/server.key").await?;
let identity = Identity::from_pem(cert, key);
let addr = "[::1]:50051".parse().unwrap();
let server = EchoServer::default();
Server::builder()
.rustls_tls(identity)
.clone()
.serve(addr, pb::server::EchoServer::new(server))
.await?;
Ok(())
}