gRPC-Gateway的使用

gRPC-Gateway官方文档

gRPC-Gateway项目地址

gRPC-Gateway使用指南

https://www.cnblogs.com/hacker-linner/p/14618862.html

https://www.lixueduan.com/posts/grpc/07-grpc-gateway/

https://www.bilibili.com/video/BV1q14y1j7nA

https://www.bilibili.com/video/BV13d4y1t7r8

之前网易的配置下发项目,用的就是这东西

即新的go-template就是基于grpc-gateway


gRPC-Gateway的作用


给grpc生成的文件附加一个http 1.1的restful供外界访问


安装


安装


1
2
3
4
5
6
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@latest

下面两条一般使用grpc时都安装过了~

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

下载gRPC-Gateway需要的两个proto


Adding gRPC-Gateway annotations to an existing proto file

google/api/http.proto

google/api/annotations.proto

在项目里建一个 google/api目录,把这两个文件拷进去


在原本的Service那里新增一个

1
2
3
4
option(google.api.http)={
post:"/api/xxxxx"
body:"*"
}

其中option(google.api.http)=是固定写法

1
2
3
4
5
protoc -I ./proto \
--go_out ./proto --go_opt paths=source_relative \
--go-grpc_out ./proto --go-grpc_opt paths=source_relative \
--grpc-gateway_out ./proto --grpc-gateway_opt paths=source_relative \
./proto/helloworld/hello_world.proto

(相较之前多了--grpc-gateway_out ./proto --grpc-gateway_opt paths=source_relative这么一行)

-I是指定pb所在的路径

之后会生成一个xxx.pb.gw.go文件


mux是grpc提供的一个东西