Examples for using protocol buffers and gRPC. Includes:
- Protocol buffers for an example CRUD service
- Go server and client implementations of the CRUD service
- Swagger for the CRUD service
- A gRPC gateway bridge that registers the CRUD service
- A Typescript gRPC web client for the CRUD service
NOTE The following commands should be run from the root of the project.
Install the protobuf compiler, protoc
.
Additional documentation on developers.google.com
Install the Go protoc plugin:
go get -u github.com/golang/protobuf/...
The following command will generate the gRPC server and client stubs for Golang:
protoc \
--proto_path=./proto \
--go_out=plugins=grpc:./go \
./proto/*.proto
It compiled the *.proto
files in the /proto
directory and adds the generated Go code to the /go
directory.
See server.go
for the example server.
See client.go
for an example client.
Install the protoc swagger plugin:
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
Swagger can then be generated with:
protoc \
--proto_path=./proto \
--swagger_out=logtostderr=true:./swagger \
./proto/*.proto
The swagger can be viewed using the Swagger editor.
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
protoc \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--proto_path=./proto \
--grpc-gateway_out=logtostderr=true:./go \
./proto/*.proto
The previous commands can also be combined into one:
protoc \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--proto_path=./proto \
--go_out=plugins=grpc:./go \
--grpc-gateway_out=logtostderr=true:./go \
--swagger_out=logtostderr=true:./swagger \
./proto/*.proto
See client.go
for an example client.
See /grpcweb
.
To produce the Typescript required for gRPC web, install the tools in package.json
protoc \
--plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \
--js_out=import_style=commonjs,binary:./js \
--ts_out=service=true:./js \
-I ./proto \
proto/*.proto proto/google/**/*.proto
The client bundle is then built with webpack:
npx webpack
Square's protowrap tool helps when compiling multiple Go protoc packages.
go get -u github.com/square/goprotowrap/cmd/protowrap
gRPC Gateway's "a bit of everything" example
Since gRPC uses HTTP 2, which requires HTTPS, knowing how to self-sign TLS certificates can help with local development.
subjectAltName
is needed for Chrome 58+
openssl req -x509 -sha256 -nodes -newkey rsa:2048 -days 1024 -subj "/C=US/ST=CO/O=AARON ELLIS LLC/CN=localhost" -reqexts SAN -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]\nsubjectAltName=DNS:localhost")) -keyout localhost.key -out localhost.crt
Add the certificate to chrome using this guide
Or enable Chrome's insecure localhost setting: chrome://flags/#allow-insecure-localhost
Happy hacking!
aodin, 2018