Adding gRPC-Gateway annotations to an existing proto file
The annotations define how gRPC services map to the JSON request and response. When using protocol buffers, each RPC must define the HTTP method and path using the google.api.http
annotation.
So we will need to add the google/api/http.proto
import to the proto file. We also need to add the HTTP->gRPC mapping we want. In this case, we’re mapping POST /v1/example/echo
to our SayHello
RPC.
See a_bit_of_everything.proto for examples of more annotations you can add to customize gateway behavior.
Now that we’ve got the gRPC-Gateway annotations added to the proto file, we need to use the gRPC-Gateway generator to generate the stubs.
We’ll need to add the gRPC-Gateway generator to the generation configuration:
version: v1
plugins:
- name: go
out: proto
opt: paths=source_relative
- name: go-grpc
opt: paths=source_relative,require_unimplemented_servers=false
- name: grpc-gateway
opt: paths=source_relative
version: v1
name: buf.build/myuser/myrepo
deps:
- buf.build/googleapis/googleapis
Then we need to run buf mod update
to select a version of the dependency to use.
And that’s it! Now if you run:
It should produce a *.gw.pb.go
file.
Using protoc
Before we can generate the stubs with protoc
, we need to copy some dependencies into our proto file structure. Copy a subset of the googleapis
from the official repository to your local proto file structure. It should look like this afterwards:
proto
│ ├── annotations.proto
│ └── http.proto
└── helloworld
└── hello_world.proto
Now we need to add the gRPC-Gateway generator to the protoc
invocation:
$ protoc -I ./proto \
--go_out ./proto --go_opt paths=source_relative \
--go-grpc_out ./proto --go-grpc_opt paths=source_relative \
--grpc-gateway_out ./proto --grpc-gateway_opt paths=source_relative \
./proto/helloworld/hello_world.proto
We also need to add and serve the gRPC-Gateway mux in our main.go
file.
For more examples, please refer to .
Testing the gRPC-Gateway
Now we can start the server:
Then we use cURL to send HTTP requests:
Hopefully, that gives a bit of understanding of how to use the gRPC-Gateway.