在golang中覆盖gRPC客户端的http主机头

问题描述 投票:0回答:1

我通过 gRPC 客户端通过连接发送请求

conn, err := grpc.Dial("hostname:port",opts...)

从服务器端,我看到http.request中的

host
是准确的
hostname:port
。然后,我的 nginx 服务器设置如下

server {
    listen port http2;
    server_name hostname;
    # ...
}
server {
    listen port http2;
    server_name another_hostname;
    # ...
} 

这是一种常见的虚拟主机技术。 无论我在

grpc.Dial(xxx:port)
中使用哪个主机名,它都可以正常工作。然而,当我把

md := metadata.New(map[string]string{"host":"another_hostname:port"})

在grpc上下文中(将填充在http2请求的标头中)。这个请求将被 nginx 阻止,我得到了

rpc error: code = Internal desc = unexpected HTTP status code received from server: 400 (Bad Request); transport: received unexpected content-type "text/html"

之所以要手动输入主机名,是因为

grpc.Dial
中的主机名是固定的。而且我不能使用不同的位置来做反向代理,因为
port
之后是restful api的路由路径。

如果主机名固定并且路由也固定,还有其他方法可以进行反向代理吗?

go header grpc http2
1个回答
0
投票

gRPC 使用 HTTP/2,不使用

:host
标头,而是使用
:authority
伪标头。此标头的值在此处确定:https://github.com/grpc/grpc-go/blob/aa6ce35c792863305e0f42acc27f2c7153275f89/clientconn.go#L1942

TL;博士

默认情况下,用于

:authority
标头的值是用户拨号目标的端点部分,其格式为
url://authority/endpoint

gRPC-Go 还支持拨号选项来覆盖此

authority
。请参阅:https://pkg.go.dev/google.golang.org/grpc#WithAuthority。但还要注意,此拨号选项会覆盖 TLS 握手期间使用的
ServerName
值。

如果您有更多问题/疑虑,请随时通过我们的 GitHub 存储库联系我们。您的疑问将在那里得到更好的响应。

© www.soinside.com 2019 - 2024. All rights reserved.