I’m trying to create an app using go grpc gateway but I faced with the problem. I integrate external service using it’s webhooks that use XML format. But as I understand grpc gateway doesn’t support request via XML so I decided to create a middleware that will convert XML to JSON in this way:
type Best2PayCallback struct {
...
}
func ConvertB2PCBToJSON(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
decoder := xml.NewDecoder(r.Body)
var callback Best2PayCallback
if err := decoder.Decode(&callback); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonData, err := json.Marshal(callback)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
r.Header.Set("Content-Type", "application/json")
r.Body = io.NopCloser(bytes.NewReader(jsonData))
next.ServeHTTP(w, r)
}
}
func (s *Server) MapHandlers() {
logger.Info("Trying to map handlers...")
authClient := authProto.NewAuthServiceClient(s.authConn)
mw := middleware.NewMDWManager(authClient)
s.mux = runtime.NewServeMux(
runtime.WithIncomingHeaderMatcher(customHeaderMatcher),
)
s.paymentServer = grpc.NewServer(
grpc.ChainUnaryInterceptor(
grpcConnector.LoggerInterceptor(),
),
)
paymentHandlers := paymentDelivery.NewHandlers()
paymentProto.RegisterPaymentServiceServer(s.paymentServer, paymentHandlers)
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
err := paymentProto.RegisterPaymentServiceHandlerFromEndpoint(ctx, s.mux, s.cfg.PaymentServer.Grpc.Host, opts)
if err != nil {
return errors.Wrap(err, "failed to register payment gRPC service gateway")
}
httpMux := http.NewServeMux()
httpMux.Handle("/b2p/listen",ConvertB2PCBToJSON(s.mux))
httpMux.Handle("/", s.mux)
logger.Infof("Serving http on %s", s.cfg.PaymentServer.Http.Host)
if err := http.ListenAndServe(s.cfg.PaymentServer.Http.Host, httpMux); err != nil {
return errors.Wrap(err, "failed to serve")
}
}
But here’s the problem: when I try to send XML request to /b2p/listen address, it says:
invalid character '<' looking for beginning of value
And I don’t understand why. I thought that it was http package problem that it try to decode xml to json but I use application/xml
header.
So what can be the problem?