wx

关注公众号领取Go学习资料

wx

洋葱小店

五、gRPC-Gateway


简介

gRPC-Gateway是protoc的一个插件。它读取gRPC服务定义并生成反向代理服务器,该服务器将RESTful JSON API转换为gRPC。此服务器根据gRPC定义中的自定义选项生成。

grpc-gateway文档

安装依赖

go get github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway

proto 文件

gateway/pb/gateway.proto 文件;其中 需要 import google/api/annotations.proto;可以将 github.com\grpc-ecosystem\grpc-gateway 下的 third_party\googleapis\google\api 文件拷贝到项目目录下;执行protoc命令

protoc -I=./gateway/pb/ -I=./third_party/ –go_out=./gateway/ –go-grpc_out=./gateway/ -grpc-gateway_out=./gateway/ ./gateway/pb/gateway.proto

syntax = "proto3";

package stream;

option go_package = "pb/;gateway";
import "google/api/annotations.proto";

message Request {
  string name = 1;
}

message Reply {
  string content = 1;
}

service GatewayDemo {
  rpc Gate(Request) returns (Reply) {
    option (google.api.http) = {
      get: "/v1/gate/{name}"
    };
  }
}

Server端

server端与正常gRPC服务没什么差别;

package main

import (
	"context"
	"fmt"
	"net"

	gateway "github.com/grpc-demo/gateway/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

type Gate struct {
	gateway.UnimplementedGatewayDemoServer
}

func (g Gate) Gate(ctx context.Context, req *gateway.Request) (*gateway.Reply, error) {
	return &gateway.Reply{
		Content: fmt.Sprintf("name:%s;", req.Name),
	}, nil
}

func main() {
	server := grpc.NewServer()
	gateway.RegisterGatewayDemoServer(server, &Gate{})
	reflection.Register(server)
	lis, _ := net.Listen("tcp", ":9000")
	_ = server.Serve(lis)
}

Http服务端

通过 gateway.RegisterGatewayDemoHandlerFromEndpoint 将http请求代理到给RPC服务;

package main

import (
	"context"
	"net/http"

	gateway "github.com/grpc-demo/gateway/pb"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const (
	// gRPC服务地址
	ServerAddr = "127.0.0.1:9000"

	ClientAddr = "127.0.0.1:8000"
)

func main() {
	ctx, cancelFunc := context.WithCancel(context.Background())
	defer cancelFunc()
	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
	err := gateway.RegisterGatewayDemoHandlerFromEndpoint(ctx, mux, ServerAddr, opts)
	if err != nil {
		panic(err)
	}
	err = http.ListenAndServe(ClientAddr, mux)
	if err != nil {
		panic(err)
	}
}

启动测试

go run server.go

访问 127.0.0.1:8000/v1/gate/grpc 同时也可以通过grpcurl 测试服务端

grpcurl -plaintext -d ‘{“name”:“grpc”}’ localhost:9000 stream.GatewayDemo/Gate

如有疑问关注公众号给我留言
wx

关注公众号领取Go学习资料

wx

洋葱小店

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo