Skip to content
This repository was archived by the owner on Jul 31, 2023. It is now read-only.

Commit 0ecb2fe

Browse files
authored
examples/grpc: send and display gRPC metadata. (#235)
1 parent c5e59c4 commit 0ecb2fe

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

examples/grpc/hello_client.cc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ int main(int argc, char **argv) {
7373
{
7474
// The client Span ends when ctx falls out of scope.
7575
grpc::ClientContext ctx;
76+
ctx.AddMetadata("key1", "value1");
77+
7678
HelloRequest request;
7779
HelloReply reply;
7880
request.set_name(name);

examples/grpc/hello_server.cc

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <grpcpp/grpcpp.h>
2323
#include <grpcpp/opencensus.h>
2424

25+
#include "absl/strings/escaping.h"
2526
#include "absl/strings/numbers.h"
2627
#include "absl/strings/str_cat.h"
2728
#include "examples/grpc/hello.grpc.pb.h"
@@ -60,6 +61,10 @@ opencensus::tags::TagKey CaseKey() {
6061
return key;
6162
}
6263

64+
absl::string_view ToStringView(const ::grpc::string_ref &s) {
65+
return absl::string_view(s.data(), s.size());
66+
}
67+
6368
// A helper function that performs some work in its own Span.
6469
void PerformWork(opencensus::trace::Span *parent) {
6570
auto span = opencensus::trace::Span::StartSpan("internal_work", parent);
@@ -87,7 +92,16 @@ class HelloServiceImpl final : public HelloService::Service {
8792
opencensus::stats::Record(
8893
{{LettersMeasure(), request->name().size()}},
8994
{{CaseKey(), isupper(request->name()[0]) ? "upper" : "lower"}});
95+
// Give feedback on stderr.
9096
std::cerr << "SayHello RPC handled.\n";
97+
std::cerr << " Metadata:\n";
98+
auto metadata = context->client_metadata();
99+
for (const auto &mdpair : metadata) {
100+
std::cerr << " \"" << absl::CEscape(ToStringView(mdpair.first))
101+
<< "\": \"" << absl::CEscape(ToStringView(mdpair.second))
102+
<< "\"\n";
103+
}
104+
std::cerr << " (end of metadata)\n";
91105
return grpc::Status::OK;
92106
}
93107
};

0 commit comments

Comments
 (0)