[英]How to do a 302 redirect in grpc-gateway
我使用grpc-gateway从我的 proto 定义中托管一个 HTTP 服务器。 整体效果很好。
但是,对于一个特殊的端点,我不想返回一个值,而是对 s3 中托管的图像进行 302 重定向。
如果你想通过 grpc-gateway 返回一个错误,你可以像这样返回它
nil, status.Error(codes.Unauthenticated, "Nope")
我想知道是否有类似的东西可以做 302 重定向?
您还可以使用WithForwardResponseOption方法,该方法允许您修改响应和响应标头。
这是我为响应设置Location
标头所做的工作。
Location
标头。 这会将Grpc-Metadata-Location
标头添加到您的响应中。func (s *Server) CreatePayment(ctx context.Context, in *proto.Request) (*proto.Response, error) {
header := metadata.Pairs("Location", url)
grpc.SendHeader(ctx, header)
return &proto.Response{}, nil
}
Grpc-Metadata-Location
标头存在于您的 GRPC 响应标头中,请同时设置 HTTP Location
标头和状态代码。func responseHeaderMatcher(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
headers := w.Header()
if location, ok := headers["Grpc-Metadata-Location"]; ok {
w.Header().Set("Location", location[0])
w.WriteHeader(http.StatusFound)
}
return nil
}
NewServeMux
一个选项:grpcGatewayMux := runtime.NewServeMux(
runtime.WithForwardResponseOption(responseHeaderMatcher),
)
没有直接的方法。 但是有一个解决方法。
gRPC 中没有类似于 302 的概念。所以简单的错误代码映射将无法正常工作。 但是您可以覆盖每个方法的响应转发器,以便它从响应中提取redirectURL
并设置 HTTP 状态代码和Location
标头。
文档链接: https : //grpc-ecosystem.github.io/grpc-gateway/docs/mapping/customizing_your_gateway/#mutate-response-messages-or-set-response-headers
查看您提到的代码,它似乎只是将grpc 状态代码直接映射到它们最接近的 http 等效项。 规范中似乎没有任何代码真正映射到 http 重定向。 假设您使用网关将浏览器连接到 grpc 服务,我是否正确?
我的建议是以某种方式重定向到协议中。 如果对某些方法的响应类似于:
message HelloResponse {
string reply = 1;
bool shouldRedirect = 2;
string redirectURL = 3;
}
然后,如果接收方可以从响应中检测到并重定向客户端。 不那么神奇,但仍然可以让您在需要时进行重定向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.