xref: /tonic/examples/src/codec_buffers/server.rs (revision 18a2b309)
1*18a2b309SKenny //! A HelloWorld example that uses a custom codec instead of the default Prost codec.
2*18a2b309SKenny //!
3*18a2b309SKenny //! Generated code is the output of codegen as defined in the `examples/build.rs` file.
4*18a2b309SKenny //! The generation is the one with .codec_path("crate::common::SmallBufferCodec")
5*18a2b309SKenny //! The generated code assumes that a module `crate::common` exists which defines
6*18a2b309SKenny //! `SmallBufferCodec`, and `SmallBufferCodec` must have a Default implementation.
7*18a2b309SKenny 
8*18a2b309SKenny use tonic::{transport::Server, Request, Response, Status};
9*18a2b309SKenny 
10*18a2b309SKenny pub mod common;
11*18a2b309SKenny 
12*18a2b309SKenny pub mod small_buf {
13*18a2b309SKenny     include!(concat!(env!("OUT_DIR"), "/smallbuf/helloworld.rs"));
14*18a2b309SKenny }
15*18a2b309SKenny use small_buf::{
16*18a2b309SKenny     greeter_server::{Greeter, GreeterServer},
17*18a2b309SKenny     HelloReply, HelloRequest,
18*18a2b309SKenny };
19*18a2b309SKenny 
20*18a2b309SKenny #[derive(Default)]
21*18a2b309SKenny pub struct MyGreeter {}
22*18a2b309SKenny 
23*18a2b309SKenny #[tonic::async_trait]
24*18a2b309SKenny impl Greeter for MyGreeter {
say_hello( &self, request: Request<HelloRequest>, ) -> Result<Response<HelloReply>, Status>25*18a2b309SKenny     async fn say_hello(
26*18a2b309SKenny         &self,
27*18a2b309SKenny         request: Request<HelloRequest>,
28*18a2b309SKenny     ) -> Result<Response<HelloReply>, Status> {
29*18a2b309SKenny         println!("Got a request from {:?}", request.remote_addr());
30*18a2b309SKenny 
31*18a2b309SKenny         let reply = HelloReply {
32*18a2b309SKenny             message: format!("Hello {}!", request.into_inner().name),
33*18a2b309SKenny         };
34*18a2b309SKenny         Ok(Response::new(reply))
35*18a2b309SKenny     }
36*18a2b309SKenny }
37*18a2b309SKenny 
38*18a2b309SKenny #[tokio::main]
main() -> Result<(), Box<dyn std::error::Error>>39*18a2b309SKenny async fn main() -> Result<(), Box<dyn std::error::Error>> {
40*18a2b309SKenny     let addr = "[::1]:50051".parse().unwrap();
41*18a2b309SKenny     let greeter = MyGreeter::default();
42*18a2b309SKenny 
43*18a2b309SKenny     println!("GreeterServer listening on {}", addr);
44*18a2b309SKenny 
45*18a2b309SKenny     Server::builder()
46*18a2b309SKenny         .add_service(GreeterServer::new(greeter))
47*18a2b309SKenny         .serve(addr)
48*18a2b309SKenny         .await?;
49*18a2b309SKenny 
50*18a2b309SKenny     Ok(())
51*18a2b309SKenny }
52