0x00

最近系统在从c++迁移到go,之前使用brpc,也需要转移到grpc,但是grpc提供的接口服务原生无法被http访问到,这对我们调试来说也很麻烦,所以需要让
grpc跟brpc一样,http也能访问rpc接口

0x01

grpc-gateway项目:

该项目是在grpc外面加一层反向代理,由代理服务器转发json格式,转变成protobuf格式来访问grpc服务,官方解释图如下:



你的grpc服务按照正常的方式启动就行了,然后根据proto文件生成gateway专有的gw.pb.go文件,然后我们重新启动一个gateway
服务,有自己独立的端口,然后有一个入口,入口就是你grpc提供服务的ip和端口。

实验

启动grpc服务



grpc提供服务的端口为7777

启动代理服务
package main import ( "flag" "github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/runtime" "golang.org/x/net/context"
"google.golang.org/grpc" "net/http" gw "data/proto" ) var ( echoEndPoint =
flag.String("echo_endpoint", "localhost:7777", "endpoint of YourService") ) func
run() error { ctx := context.Background() ctx, cancel :=
context.WithCancel(ctx)defer cancel() mux := runtime.NewServeMux() opts :=
[]grpc.DialOption{grpc.WithInsecure()} err :=
gw.RegisterGreeterHandlerFromEndpoint(ctx, mux, *echoEndPoint, opts)if err !=
nil { return err } return http.ListenAndServe(":8989", mux) } func main() {
flag.Parse()defer glog.Flush() if err := run(); err != nil { glog.Fatal(err) } }
gateway的端口为8989,endpoint指向了grpc服务的端口7777。

postman访问



访问成功

缺点

* 需要开2个端口
* 写多余的代码
理想情况下应该有个插件自己把http请求转换成proto的方式,犹如brpc一样

解决方法

后来发现https的方式是可以解决上面的问题,grpc和https端口在一起,也不用起两个服务。

grpc https gateway
<https://segmentfault.com/a/1190000008106582?utm_source=tuicool&utm_medium=referral>

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信