Background
gRPC is great -- it generates API clients and server stubs in many
programming languages, it is fast, easy-to-use, bandwidth-efficient and its
design is combat-proven by Google. However, you might still want to provide a
traditional RESTful API as well. Reasons can range
from maintaining backwards-compatibility, supporting languages or clients not
well supported by gRPC to simply maintaining the
aesthetics and tooling involved with a RESTful
architecture.
This project aims to
provide that HTTP+JSON interface to your gRPC
service. A small amount of configuration in your service to attach HTTP
semantics is all that's needed to generate a reverse-proxy with this library.
Installation
First you need to
install ProtocolBuffers 3.0.0 or later.
mkdir tmp
cd tmp
git
clone https://github.com/protocolbuffers/protobuf
cd protobuf
./autogen.sh
./configure
make
make check
sudo
make install
Then, go get -u as usual the following packages:
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-go
Usage
Make sure that
your $GOPATH/bin is in your $PATH.
your_service.proto:
syntax = "proto3";
package example;
message StringMessage {
string value = 1;
}
service YourService {
rpc
Echo(StringMessage) returns (StringMessage)
{}
}
+import "google/api/annotations.proto";
- rpc
Echo(StringMessage) returns (StringMessage)
{}
+ rpc Echo(StringMessage) returns (StringMessage)
{
+ option (google.api.http)
= {
4.
protoc -I/usr/local/include -I. \
6.
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
\
It will generate
a stub file path/to/your_service.pb.go.
protoc -I/usr/local/include
-I. \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
\
protoc -I/usr/local/include
-I. \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
\
--plugin=protoc-gen-grpc=grpc_ruby_plugin \
10.
protoc -I/usr/local/include -I. \
12.
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
\
13.
--grpc-gateway_out=logtostderr=true:. \
It will generate
a reverse proxy path/to/your_service.pb.gw.go.
Now you need to
write an entrypoint of the proxy server.
"github.com/grpc-ecosystem/grpc-gateway/runtime"
gw
"path/to/your_service_package"
echoEndpoint
= flag.String("echo_endpoint", "localhost:9090", "endpoint
of YourService")
ctx,
cancel := context.WithCancel(ctx)
opts := []grpc.DialOption{grpc.WithInsecure()}
err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint,
opts)
return http.ListenAndServe(":8080", mux)
16.
protoc -I/usr/local/include -I. \
18.
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
\