How to do a 302 redirect in grpc-gateway
you could also use runtime. WithForwardResponseOption method which allows you to modify your response and response headers.
here is what I did to set Location
header in response.
- Set
Location
header in your GRPC method using metadata. this addsGrpc-Metadata-Location
header to your response.
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
}
- If
Grpc-Metadata-Location
header exists in your GRPC response headers, Set HTTPLocation
header and status code as well.
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
}
- Set this func as an Option in
NewServeMux
:
grpcGatewayMux := runtime.NewServeMux(
runtime.WithForwardResponseOption(responseHeaderMatcher),
)
There's no straightforward way. But there's a workaround.
There's no conception in gRPC similar to 302. So simple error code mappings won't work fine.
But you can overwrite a response forwarder per method so that it extracts redirectURL
from the response and sets the HTTP status code and Location
header.
https://grpc-ecosystem.github.io/grpc-gateway/docs/mapping/customizingyourgateway/#mutate-response-messages-or-set-response-headers