现有服务是用micro+protobuf+gRPC。现在每个服务都有个proto文件,完整定义了参数、传递消息及响应结果。主要实现步骤有三步
1. 用.proto文件转换为swagger.json文件
2. 合并所有swagger.json成为一个
3. Serve the API
Step 1: .proto文件转换为swagger.json文件
使用工具:https://github.com/grpc-ecosystem/grpc-gateway
Install
protoc
和proto-gen-go
的安装略
Usage
- 正常写.proto文件
syntax = "proto3";
|
|
package example;
|
|
message StringMessage {
|
|
string value = 1;
|
|
}
|
|
service YourService {
|
|
rpc Echo(StringMessage) returns (StringMessage) {}
|
|
}
|
- 添加
自定义选项
到这个.proto文件
syntax = "proto3";
|
|
package example;
|
|
+
|
|
+import "google/api/annotations.proto";
|
|
+
|
|
message StringMessage {
|
|
string value = 1;
|
|
}
|
|
service YourService {
|
|
- rpc Echo(StringMessage) returns (StringMessage) {}
|
|
+ rpc Echo(StringMessage) returns (StringMessage) {
|
|
+ option (google.api.http) = {
|
|
+ post: "/v1/example/echo"
|
|
+ body: "*"
|
|
+ };
|
|
+ }
|
|
}
|
- 生成 swagger.json文件
protoc -I/usr/local/include -I.
|
|
-I$GOPATH/src
|
|
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
|
|
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway
|
|
--swagger_out=logtostderr=true:.
|
|
path/to/your_service.proto
|
增加更多的swagger注释
import "google/api/annotations.proto";
|
|
import "protoc-gen-swagger/options/annotations.proto";
|
|
// 概要
|
|
option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = {
|
|
info: {
|
|
title: "go-service"
|
|
version : "1.0.0"
|
|
description: "gRPC服务用"
|
|
};
|
|
schemes: HTTP
|
|
consumes: "application/json"
|
|
produces: "application/json"
|
|
};
|
|
// 服务介绍,tag
|
|
service YourService {
|
|
rpc Echo(RequestById) returns (City) {
|
|
option (google.api.http) = {
|
|
post: "/v1/example/echo"
|
|
body: "*"
|
|
};
|
|
option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = {
|
|
summary: "详情"
|
|
tags: "example"
|
|
};
|
|
}
|
|
}
|
|
更多可配置的可参照这里:github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.proto
Step 2: 合并swagger.json文件
每个proto文件只能生成一个json文件,因此需要把各个json文件合并成一个。
使用工具:https://github.com/go-swagger/go-swagger
Install
brew tap go-swagger/go-swagger
|
|
brew install go-swagger
|
Usage
主要使用mixin
命令
swagger mixin {spec1} {spec2}
|
为了方便可以写个bash脚本,把所有生成的*.swagger.json
文件合并起来。
Step 3: Serve the API
swagger serve swagger.json
|
|
swagger serve swagger.json -Fswagger
|
第一个只能看文档
第二个会引导你打开某链接,实际是swagger ui的live demo
为了“try it out”能成功,不要忘记在swagger.json
里加入host
和basePath
。
服务器上搭就是拉了份swagger UI,把host的url改为了这个swagger.json
可以访问的地址,即可。
其它改动:
以前用来生成stub的命令要增加path:
比如,before:
protoc -I$GOPATH/src:. --micro_out=. --go_out=. path/to/your_service.proto
|
after:
protoc -I/usr/local/include -I.
|
|
-I$GOPATH/src
|
|
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis
|
|
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway
|
|
--micro_out=. --go_out=.
|
|
path/to/your_service.proto
|