Skip to content

Commit

Permalink
examples: add client example for tonic-reflection
Browse files Browse the repository at this point in the history
This adds an example usage of the `ServerReflectionClient` using
a `ListServices` request.

Fixes: hyperium#1600
  • Loading branch information
grottohub committed Jan 12, 2024
1 parent 177c1f3 commit 7dc4731
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/Cargo.toml
Expand Up @@ -164,6 +164,11 @@ name = "health-server"
path = "src/health/server.rs"
required-features = ["health"]

[[bin]]
name = "reflection-client"
path = "src/reflection/client.rs"
required-features = ["reflection"]

[[bin]]
name = "reflection-server"
path = "src/reflection/server.rs"
Expand Down
44 changes: 44 additions & 0 deletions examples/src/reflection/client.rs
@@ -0,0 +1,44 @@
use tokio_stream::StreamExt;
use tonic_reflection::pb::{
server_reflection_client::ServerReflectionClient, server_reflection_request::MessageRequest,
server_reflection_response::MessageResponse, ServerReflectionRequest, ServerReflectionResponse,
};

fn parse_response(resp: ServerReflectionResponse) {
let message_response = resp.message_response.expect("message response");

if let MessageResponse::ListServicesResponse(list_response) = message_response {
for svc in list_response.service {
println!("\tfound service: `{}`", svc.name);
}
}
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let conn = tonic::transport::Endpoint::new("http://[::1]:50052")?
.connect()
.await?;

let mut client = ServerReflectionClient::new(conn);

let list_services_request = ServerReflectionRequest {
host: "host".into(),
message_request: Some(MessageRequest::ListServices("list".into())),
};

let request_stream = tokio_stream::once(list_services_request);
let mut inbound = client
.server_reflection_info(request_stream)
.await?
.into_inner();

while let Some(recv) = inbound.next().await {
match recv {
Ok(resp) => parse_response(resp),
Err(e) => println!("\tdid not receive response due to error: `{}`", e),
}
}

Ok(())
}

0 comments on commit 7dc4731

Please sign in to comment.