| 1 |
# Metadata Example |
| 2 |
|
| 3 |
## Overview |
| 4 |
|
| 5 |
This example shows you how to add custom headers on the client and server and |
| 6 |
how to access them. |
| 7 |
|
| 8 |
Custom metadata must follow the "Custom-Metadata" format listed in |
| 9 |
https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md, with the |
| 10 |
exception of binary headers, which don't have to be base64 encoded. |
| 11 |
|
| 12 |
### Get the tutorial source code |
| 13 |
The example code for this and our other examples lives in the `examples` directory. Clone this repository |
| 14 |
at the [latest stable release tag](https://github.com/grpc/grpc/releases) to your local machine by running the following command: |
| 15 |
```sh |
| 16 |
$ git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc |
| 17 |
``` |
| 18 |
Change your current directory to examples/cpp/metadata |
| 19 |
```sh |
| 20 |
$ cd examples/cpp/metadata |
| 21 |
``` |
| 22 |
|
| 23 |
### Generating gRPC code |
| 24 |
To generate the client and server side interfaces: |
| 25 |
```sh |
| 26 |
$ make helloworld.grpc.pb.cc helloworld.pb.cc |
| 27 |
``` |
| 28 |
Which internally invokes the proto-compiler as: |
| 29 |
```sh |
| 30 |
$ protoc -I ../../protos/ --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin ../../protos/helloworld.proto |
| 31 |
$ protoc -I ../../protos/ --cpp_out=. ../../protos/helloworld.proto |
| 32 |
``` |
| 33 |
### Try it! |
| 34 |
Build client and server: |
| 35 |
|
| 36 |
```sh |
| 37 |
$ make |
| 38 |
``` |
| 39 |
|
| 40 |
Run the server, which will listen on port 50051: |
| 41 |
|
| 42 |
```sh |
| 43 |
$ ./greeter_server |
| 44 |
``` |
| 45 |
|
| 46 |
Run the client (in a different terminal): |
| 47 |
|
| 48 |
```sh |
| 49 |
$ ./greeter_client |
| 50 |
``` |
| 51 |
|
| 52 |
If things go smoothly, you will see in the client terminal: |
| 53 |
|
| 54 |
"Client received initial metadata from server: initial metadata value" |
| 55 |
"Client received trailing metadata from server: trailing metadata value" |
| 56 |
"Client received message: Hello World" |
| 57 |
|
| 58 |
|
| 59 |
And in the server terminal: |
| 60 |
|
| 61 |
"Header key: custom-bin , value: 01234567" |
| 62 |
"Header key: custom-header , value: Custom Value" |
| 63 |
"Header key: user-agent , value: grpc-c++/1.16.0-dev grpc-c/6.0.0-dev (linux; chttp2; gao)" |
| 64 |
|
| 65 |
We did not add the user-agent metadata as a custom header. This shows how |
| 66 |
the gRPC framework adds some headers under the hood that may show up in the |
| 67 |
metadata map. |