gRPC-gateway使用介绍

gRPC-gateway

参考资料:gRPC-Gateway使用指南

服务中,使用了gRPC gateway(代理)来将外部的http请求映射为内部rpc调用。

proto文件示例:

protobuf 复制代码
// 导入google/api/annotations.proto
import "google/api/annotations.proto";

rpc List(ListRequest) returns (ListResponse) {
        option (google.api.http) = {
            post : "/project/Service/List"
        };
    }

接下来还需进行一些配置才能完成映射。

示例代码:

(8080端口提供gRPC API服务,8090端口提供HTTP API服务)

go 复制代码
import (
	"context"
	"log"
	"net"
	"net/http"

	helloworldpb "github.com/Q1mi/greeter/proto/helloworld"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime" // 注意v2版本
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type server struct {
	helloworldpb.UnimplementedGreeterServer
}

func NewServer() *server {
	return &server{}
}

func (s *server) SayHello(ctx context.Context, in *helloworldpb.HelloRequest) (*helloworldpb.HelloReply, error) {
	return &helloworldpb.HelloReply{Message: in.Name + " world"}, nil
}

func main() {
	// Create a listener on TCP port
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalln("Failed to listen:", err)
	}

	// 创建一个gRPC server对象
	s := grpc.NewServer()
	// 注册Greeter service到server
	helloworldpb.RegisterGreeterServer(s, &server{})
	// 8080端口启动gRPC Server
	log.Println("Serving gRPC on 0.0.0.0:8080")
	go func() {
		log.Fatalln(s.Serve(lis))
	}()

	// 创建一个连接到我们刚刚启动的 gRPC 服务器的客户端连接
	// gRPC-Gateway 就是通过它来代理请求(将HTTP请求转为RPC请求)
	conn, err := grpc.DialContext(
		context.Background(),
		"0.0.0.0:8080",
		grpc.WithBlock(),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		log.Fatalln("Failed to dial server:", err)
	}

	gwmux := runtime.NewServeMux()// <--<--
	// 注册Greeter
	err = helloworldpb.RegisterGreeterHandler(context.Background(), gwmux, conn)
	if err != nil {
		log.Fatalln("Failed to register gateway:", err)
	}

	gwServer := &http.Server{
		Addr:    ":8090",
		Handler: gwmux, // <--<-- 该endpoint接收到http请求时,会调用grpc-gateway内部的方法完成映射
	}
	// 8090端口提供gRPC-Gateway服务
	log.Println("Serving gRPC-Gateway on http://0.0.0.0:8090")
	log.Fatalln(gwServer.ListenAndServe())
}
相关推荐
喵个咪16 小时前
GoWind IM 场景:乙方怎么用一套 IM 平台交付多个客户——档位、租户与离线交付
后端·go·saas
郝学胜-神的一滴2 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
里海_go2 天前
Go 语言内存管理机制详解
go
斐波那契数列2 天前
没有 JSX,也能在 Go 里写 React 风格 GUI:Tenon 的架构与性能实践
go
花椒技术2 天前
花椒语音房联机五子棋:Go 服务端如何保证一回合只落一颗子
websocket·go
Sailing3 天前
🚀客户端都超时了,你的 Go 服务还在查库?Context 取消链路不打通,连接池迟早被打爆
后端·面试·go
小满zs3 天前
Go语言第二十一章(Gin上传文件)
后端·go
我不会起名字3223 天前
Agent 总调错工具?MCP 接进 Go 后端的 4 个约束
后端·go·agent·mcp
如夏倾城5 天前
BGP(Border Gateway Protocol 边界网关协议)
运维·服务器·网络·gateway·信息与通信
我不会起名字3226 天前
WebSocket 停机与在线状态:Shutdown 返回后还需要清理什么
redis·后端·websocket·go·即时通讯·im·故障排查