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:

    1. version: v1
    2. plugins:
    3. - name: go
    4. out: proto
    5. opt: paths=source_relative
    6. - name: go-grpc
    7. opt: paths=source_relative,require_unimplemented_servers=false
    8. - name: grpc-gateway
    9. opt: paths=source_relative
    1. version: v1
    2. name: buf.build/myuser/myrepo
    3. deps:
    4. - 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:

    1. proto
    2. ├── annotations.proto
    3. └── http.proto
    4. └── helloworld
    5. └── hello_world.proto

    Now we need to add the gRPC-Gateway generator to the protoc invocation:

    1. $ protoc -I ./proto \
    2. --go_out ./proto --go_opt paths=source_relative \
    3. --go-grpc_out ./proto --go-grpc_opt paths=source_relative \
    4. --grpc-gateway_out ./proto --grpc-gateway_opt paths=source_relative \
    5. ./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.