有关GPRC 的创建 大家 请参考 go学习笔记 Windows Go 1.15 以上版本的 GRPC 通信【自签CA和双向认证】,本文同样会用上文创建的证书。【注意我的环境是win7+go1.15.6】
1:将REST注释添加到API定义,我们必须安装grpc-gateway和swagger文档生成器插件
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
go get -u -v github.com/golang/protobuf/protoc-gen-g
先看看我文件夹的结构吧:
2创建 /api/proto/v1/todo.protor然后生成 ,你可以在这里获得proto语言规范:https://developers.google.com/protocol-buffers/docs/proto3,这里增加了swagger的配置,这个配置的作用是让swagger把远程调用配置成http,如果没有这些配置,swagger默认的远程调用就是https的,本文的gRPC-Gateway提供的是http服务,所以要加上这些配置
syntax = "proto3";
package protos;
// 1 导入 gateway 相关的proto 以及 swagger 相关的 proto
import "google/api/annotations.proto";
import "protoc-gen-swagger/options/annotations.proto";
// 2 定义 swagger 相关的内容
option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = {
info: {
title: "grpc gateway sample";
version: "1.0";
license: {
name: "MIT";
};
};
schemes: HTTP;
consumes: "application/json";
produces: "application/json";
};
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {
// 3 标识接口路由
option (google.api.http) = {
post: "/hello_world"
body: "*"
};
}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
生成命令如下,
1.如果编译遇到Interpreting non ascii codepoint 194. 类似错误【说白了就是有肉眼看不见的一些东