Skip to content

gRPC Controllers

In Sword, a gRPC controller is a struct annotated with #[controller(kind = Controller::Grpc, ...)] that implements the trait generated by tonic.

Defining a Controller

rust
use sword::grpc::*;
use sword::prelude::*;

#[controller(kind = Controller::Grpc, service = UserGrpcServiceServer)]
pub struct UsersController;

#[sword::grpc::async_trait]
impl UserGrpcService for UsersController {
    async fn list_users(
        &self,
        req: Request<ListUsersRequest>,
    ) -> GrpcResult<ListUsersReply> {
        tracing::info!("ListUsers gRPC method called");

        Ok(Response::new(ListUsersReply { users: vec![] }))
    }
}

The trait (UserGrpcService) is generated by tonic from a .proto file and must be imported to implement the controller.

Registering in a Module

rust
use sword::prelude::*;

pub struct UsersModule;

impl Module for UsersModule {
    fn register_controllers(controllers: &ControllerRegistry) {
        controllers.register::<UsersController>();
    }
}

See Also