gRPC server/client example with REST gateway (see https://github.com/grpc-ecosystem/grpc-gateway) written in Go.
This is a simple echo server implementation that returns the requested message.
If you have a running docker system you can use the supplied protoc-gen.sh script to generate the required protocol buffers source files.
./scripts/protoc-gen.shThis should update/generate the required source files:
pkg/api/service.pb.go
pkg/api/service.pb.gw.goAlternatively to the docker way, you can install protoc on your system (see protocol buffers docs) and generate the sources locally.
The following dependencies are required:
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
go get -u github.com/golang/protobuf/protoc-gen-goThese enable protoc to generate Go sources for the gRPC gateway and provide us with a swagger file on top of that.
Now you should be able to run the following command:
protoc \
-I . \
-I /usr/local/include \
-I ${GOPATH}/src \
-I ${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--proto_path=api/proto \
--go_out=plugins=grpc:pkg/api \
--grpc-gateway_out=logtostderr=true:pkg/api \
--swagger_out=logtostderr=true:api/swagger \
service.protoThe project utilises Go Modules for the versioning of dependencies, thus Go in version >1.11 is required to reliably build the project.
Also ensure that Modules are enabled:
echo GO111MODULE=ongo build ./cmd/servergo build ./cmd/grpc-clientTo start the server execute the following:
./serverBy default the gRPC server runs on port 8082 and the HTTP server/REST gateway on port 8080.
Custom bind ports can be set via command line parameters:
./server -grpc-port 9092 -http-port 9090The grpc-client automatically sends the message Hello world! to the gRPC server running on localhost:8082.
./grpc-client
{"level":"info","msg":"Response: echo.EchoMessage{Value:\"Hello world!\"}","time":"2019-04-03T14:43:40+02:00"}To send different messages to different ports/addresses use:
./grpc-client -server-addr localhost:9092 -echo-message "Hello gRPC\!"
{"level":"info","msg":"Response: echo.EchoMessage{Value:\"Hello gRPC!\"}","time":"2019-04-03T14:45:26+02:00"}Alternatively we can use cURL to query the REST endpoint:
curl -X POST http://localhost:8080/echo -d '{"value":"Hello REST gateway!"}'
{"value":"Hello REST gateway!"}