References:
- grpc-gateway
- CoreOS blog post Take a REST with HTTP/2, Protobufs, and Swagger
- Phillip's grpc gateway example
This is a convenience library and code-generation tool for
creating a grpc server with a REST gateway and Swagger-ui
description from proto files.
grpcgw is a library extracted and modified from the example in Phillip's github page. It enables the user to write a service without effort and minimal boiler plate code.
go get -u github.com/posener/grpcgw/gen
This directory contains a basic example of echo server. Lets examine the code:
-
example/serviceThis directory contains the service main business.
-
service.proto: The RPC/Rest API of the service, represented with protobuf and the grpc-gw extension. There you could find the definition of theEchoMessagemessage, theEchoServiceinterface, and theEchomethod of that interface. -
service.go: The business logic of the service. There you could find theservicestruct, implementing theEchoServiceinterface, and theEchomethod, which is the implementation of the interface.You could also find there functions that creates new service and new client.
-
register.go: Methods implementing thegrpcgw.Serviceinterface. Those methods are used to register theservicewhen the server starts. -
After invoking the
go genenratecommand in theexampleproject, two more files will appear in this folder:service.pb.gowhich is the implementation of the grpc server, andservice.pb.gw.go, which is the implementation of the REST gateway. In theexampledirectory, aswaggerdirectory will appear with auto-generated swagger json.
-
-
generate.go: A file containing the auto-generation script. -
main.goandcmd/*are auto generated with (cobra)[https://github.com/spf13/cobra].-
grpcgw provides basic commands to start and stop the client. In the
main.gowe callgrpcgw.AddCommands(cmd.RootCmd, example.NewService()), which customize theservecommand to use theexampleservice. -
cmd/echo.gois the echo sub-command, notice that it usesgrpcgw.NewGRPCConnection()to get connection to the defined server.
-
-
Makefile: can give an impression about how to create your own service and how to run it. You can play with theruntarget, which will also create certificates for your server and run it. Therun-client-echotarget will send an RPC to the running server. Therun-rest-echotarget will send the same request through REST. -
When the server is running, browse to https://localhost:10000/swagger-ui, then, enter in the text box: https://localhost:10000/swaggers/service.swagger.json.
This script easily creates from a proto file the following
files:
-
.pb.go: A grpc service for the service described in the proto. -
.pb.gw.go: A gateway service for the REST endpoints described proto. -
json.gofile: Containing the json representation of a swagger file which described the REST endpoints. This file is to be used with the swagger-ui service.
go get -u github.com/posener/grpcgw/gen
gen -swagger-out <swagger go file> <proto file> [<proto file>...]