github project: https://github.com/denisbog/proto/
project that implements ping service with Tonic in Rust
protocol definition:
syntax = "proto3";
package ping;
service Ping { rpc ping(PingRequest) returns (PingResponse); }
message PingRequest { string message = 1; }
message PingResponse { StatusCode statusCode = 1; }
enum StatusCode {
FAILURE = 0;
SUCCESS = 1;
}
server:
use ping::{
ping_server::{Ping, PingServer},
PingRequest, PingResponse, StatusCode,
};
use tonic::{transport::Server, Request, Response, Status};
pub mod ping {
tonic::include_proto!("ping");
}
struct PingImpl {}
#[tonic::async_trait]
impl Ping for PingImpl {
async fn ping(&self, request: Request<PingRequest>) -> Result<Response<PingResponse>, Status> {
println!("processing request {:?}", request.into_inner().message);
Ok(Response::new(PingResponse {
status_code: StatusCode::Success.into(),
}))
}
}
#[tokio::main]
async fn main() {
Server::builder()
.add_service(PingServer::new(PingImpl {}))
.serve("[::0]:50001".parse().unwrap())
.await
.unwrap()
}
client:
use std::env;
use ping::{ping_client::PingClient, PingRequest};
use tonic::Request;
pub mod ping {
tonic::include_proto!("ping");
}
#[tokio::main]
async fn main() {
let mut client = PingClient::connect(format!(
"http://{}:50001",
env::var("PING_SERVER").unwrap_or("[::0]".into())
))
.await
.unwrap();
let response = client
.ping(Request::new(PingRequest {
message: "this is a ping request".into(),
}))
.await
.unwrap();
println!(
"received response {:?}",
response.into_inner().status_code()
);
}
github action:
name: Rust
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Install Protoc
uses: arduino/setup-protoc@v2
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose