1、gateway集成swagger
1、为了简化实战过程,gRPC-Gateway
暴露的服务并未使用https
,而是http
,但是swagger-ui
提供的调用服
务却是https
的,因此要在proto
文件中指定swagger
以http
调用服务,指定的时候会用到文件
protoc-gen-swagger/options/annotations.proto
,因此需要找到这个文件对应的包,放在合适的位置。
2、swaggerdemo.swagger.json
:这是swagger-ui
要用的json
文件,依据此文件,swagger
才能正确的展现
出gRPC-Gateway
暴露的服务和参数定义,可以在页面上发起请求,此文件由插件protoc-gen-swagger
生成。
3、在gRPC-Gateway
的代码中集成swagger-ui
的代码:swagger-ui
的代码由多个png、html、js
文件组成,
需要用工具go-bindata
转换成go
源码并放入合适的位置,流程如下图:
4、要将swaggerdemo.swagger.json
文件通过web
暴露出来,需要工具go-bindata-assetfs
。
5、使用swagger
的方式:打开swagger-ui
页面后,将swaggerdemo.swagger.json
输入给swagger-ui
页面,
令其解析后,生成对应的在线接口服务。
1.1 安装必要的go包
1、安装protoc-gen-swagger
$ go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
$ go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
2、go-bindata
用来将swagger-ui
的源码转为GO代码:
$ go install github.com/jteeuwen/go-bindata/...
3、go-bindata-assetfs
在应用启动后,对外提供文件服务,这样可以通过web
访问swagger
的json
文件:
$ go install github.com/elazarl/go-bindata-assetfs/...
4、glog
是常用的日志工具:
$ go get -u github.com/golang/glog
1.2 编写proto文件
新建swaggerdemo.proto
:
// 协议类型
syntax = "proto3";
// 包名
package swaggerdemo;
option go_package="./protoc;swaggerdemo";
import "google/api/annotations.proto";
import "protoc-gen-swagger/options/annotations.proto";
// 定义swagger内容
option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = {
info: {
title: "grpc gateway helloworld sample";
version: "1.0";
};
schemes: HTTP;
};
// 定义的服务名
service Greeter {
// 具体的远程服务方法
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
post: "/helloworld"
body: "*"
};
}
}
// SayHello方法的入参,只有一个字符串字段
message HelloRequest {
string name = 1;
}
// SayHello方法的返回值,只有一个字符串字段
message HelloReply {
string message = 1;
}
protoc-gen-swagger/options/annotations.proto
来自于:
github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
生成swaggerdemo.pb.go
,gRPC所需的go文件:
$ protoc --go_out=plugins=grpc:. protoc/swaggerdemo.proto
生成swaggerdemo.pb.gw.go
,gRPC-Gateway所需的go文件:
$ protoc --grpc-gateway_out=logtostderr=true:. protoc/swaggerdemo.proto
生成swaggerdemo.swagger.json
,swagger-ui
要用的json
文件,依据此文件,swagger
展现的页面中会有
gRPC-Gateway
暴露的服务和参数定义,可以在页面上发起请求:
$ protoc --swagger_out=logtostderr=true:. protoc/swaggerdemo.proto
1.3 生成swagger-ui的go文件
从 https://github.com/swagger-api/swagger-ui
下载包,解压把dist
目录下的所有文件拷贝我们项目的
/swagger/swagger-ui/
目录下。
运行指令把Swagger UI
转成datafile.go
代码:
$ go-bindata --nocompress -pkg swagger -o swagger/datafile.go swagger/swagger-ui/...