grpc提供http访问方式

0x00

最近系统在从c++迁移到go,之前使用brpc,也需要转移到grpc,但是grpc提供的接口服务原生无法被http访问到,这对我们调试来说也很麻烦,所以需要让grpcbrpc一样,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的端口为8989endpoint指向了grpc服务的端口7777

postman访问

这里写图片描述

访问成功

缺点

  • 需要开2个端口
  • 写多余的代码

理想情况下应该有个插件自己把http请求转换成proto的方式,犹如brpc一样

解决方法

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

grpc https gateway

20190621更新

同事用https://github.com/soheilhy/cmux把多个协议的服务都绑定到一起了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章