如何在 grpc-gateway 中进行 302 重定向

Umu*_*zer 6 go grpc-gateway

我使用grpc-gateway从我的 proto 定义中托管一个 HTTP 服务器。整体效果很好。

但是,对于一个特殊的端点,我不想返回一个值,而是对 s3 中托管的图像进行 302 重定向。

如果你想通过 grpc-gateway 返回一个错误,你可以像这样返回它

nil, status.Error(codes.Unauthenticated, "Nope")
Run Code Online (Sandbox Code Playgroud)

我想知道是否有类似的东西可以做 302 重定向?

就我从该页面获得的信息而言,似乎不太可能。我希望我忽略了一些东西。

rez*_*zam 7

您还可以使用WithForwardResponseOption方法,该方法允许您修改响应和响应标头。

Location这是我为响应设置标头所做的事情。

  1. Location使用元数据在 GRPC 方法中设置标头。这会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
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果Grpc-Metadata-LocationGRPC 响应标头中存在标头,请Location同时设置 HTTP 标头和状态代码。
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
}
Run Code Online (Sandbox Code Playgroud)
  1. 将此函数设置为选项NewServeMux
grpcGatewayMux := runtime.NewServeMux(
    runtime.WithForwardResponseOption(responseHeaderMatcher),
)
Run Code Online (Sandbox Code Playgroud)


小智 3

没有直接的方法。但有一个解决方法。

gRPC 中没有类似于 302 的概念。因此简单的错误代码映射无法正常工作。但是您可以覆盖每个方法的响应转发器,以便它redirectURL从响应中提取并设置 HTTP 状态代码和Location标头。

文档链接: https://grpc-ecosystem.github.io/grpc-gateway/docs/mapping/customizing_your_gateway/#mutate-response-messages-or-set-response-headers