Implementing a gRPC Server
Serve unary RPC methods.
The Generated Server Trait
For a service named Greeter, tonic generates a trait in greeter_server. You implement it on your own struct to provide behavior.
The trait is async via #[tonic::async_trait], so each method is an async fn returning a Result.
use greeter::v1::greeter_server::{Greeter, GreeterServer};
use greeter::v1::{HelloRequest, HelloReply};Request and Response Wrappers
Methods take a tonic::Request<T> and return a tonic::Response<T>. These wrappers carry metadata, extensions, and the inner message.
Call .into_inner() to get the decoded message, and Response::new(..) to build a reply.
let req: HelloRequest = request.into_inner();
let reply = HelloReply { message: format!("Hi {}", req.name) };
Ok(Response::new(reply))All lessons in this course
- Protobuf and Service Definitions
- Generating Code with tonic-build
- Implementing a gRPC Server
- Calling from a gRPC Client