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())
}
相关推荐
4SAPI8 小时前
会议智能处理大模型 API 生产选型指南:4SAPI、硅基流动与 OpenRouter 的架构权衡
人工智能·架构·自动化·gateway·php
FungLeo11 小时前
成为全栈·Go 后端篇·跨语言认证兼容:Node 与 Go 如何互认 JWT 和密码
golang·go·jwt·身份认证·成为全栈·bcrypt
JJJennie77714 小时前
MAI Gateway实战部署:大模型网关部署方案?从0到1上手指南
数据库·人工智能·gateway·ai网关
FungLeo15 小时前
成为全栈·Go 后端篇·重写之前先锁基线:契约、Node 版本与行为清单
golang·node.js·go·openapi·契约测试·成为全栈
小满zs1 天前
Go语言第十七章(反射)
后端·go
小满zs1 天前
Go语言第十五章(JSON序列化)
后端·go
小满zs1 天前
Go语言第十六章(自定义类型)
后端·go
w-w0w-w1 天前
Go语言学习day1
go
FungLeo1 天前
成为全栈·Go 后端篇·契约一致性与差分测试:两套实现如何互相校验
golang·node.js·go·合约测试·差分测试·成为全栈·api兼容
vipxieliang2 天前
Go 1.25 Green Tea GC 深度解析:以页为单位的垃圾回收新范式
go