gpt4 book ai didi

javascript - 如何使用 grpc-web 进行流式传输并在同一端口上使用 REST API?

转载 作者:行者123 更新时间:2023-12-03 10:09:18 27 4
gpt4 key购买 nike

我在 Go 中有一个使用 cmux 的服务器允许多个协议(protocol)在同一个端口上运行,但是 README 中指定了一个限制,即

cmux matches the connection when it's accepted. For example, one connection can be either gRPC or REST, but not both. That is, we assume that a client connection is either used for gRPC or REST.


我需要浏览器能够从 grpc-web 流式传输并在同一端口上调用 REST API,但浏览器重用相同的连接并导致多路复用不起作用。

最佳答案

这是一个非常棘手的问题。由于浏览器更喜欢使用现有的 TCP 连接进行流水线操作,因此多路复用器往往会将数据包发送到错误的协议(protocol)处理程序,例如它可能会发送 grpc-web数据包到 REST,反之亦然。幸运的是,有一个非常简单的解决方案:

package main

listener := net.Listen("tcp", ":2289")
multiplexer := cmux.New(listener)
grpcListener := multiplexer.Match(cmux.HTTP2())
httpListener := multiplexer.Match(cmux.HTTP1Fast())
grpcServer := grpc.Server()
wrappedGrpc := grpcweb.WrapServer(grpcServer)
go func() {
httpServer := echo.New()
(&http.Server{
Handler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if strings.Contains(req.Header.Get("Access-Control-Request-Headers"), "x-grpc-web") || req.Header.Get("x-grpc-web") == "1" || req.Header.Get("Sec-Websocket-Protocol") == "grpc-websockets" {
inst.API.GrpcWebServer.ServeHTTP(resp, req)
} else {
httpServer.ServeHTTP(resp, req)
}
}),
}).Serve(httpListener)
}()

go func() {
grpcServer.Serve(grpcListener)
}()

go func() {
multiplexer.Serve()
}()
这是如何运作的?
本质上,而不是使用 cmux的默认多路复用(仅对每个连接进行多路复用)我们在所有传入的 HTTP 请求上注册了一个新的迷你 http 服务器处理程序,然后我们可以显式检查 header 并直接调用处理程序。

关于javascript - 如何使用 grpc-web 进行流式传输并在同一端口上使用 REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65152939/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com