grpc-ecosystem / grpc-gateway

gRPC to JSON proxy generator following the gRPC HTTP spec

Home Page:https://grpc-ecosystem.github.io/grpc-gateway/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fetching request body in the customErrorHandler middleware

lsgndln opened this issue Β· comments

πŸ› Bug Report

Inside a custom error handler middleware with the WithErrorHandler option, I can't access the request body payload (for logging purpose for example). It seems empty (because it was probably already read) How could I do achieve this ?

To Reproduce

  1. In the NewServeMux function, pass a WithErrorHandler custom error handler function
	return grpcgw.NewServeMux(
                ...
		grpcgw.WithErrorHandler(customErrorHandler(logger)),
	)
  1. In the customErrorHandler function, try to log the request body. It is empty, probably because it has been read before.
return func(ctx context.Context, mux *grpcgw.ServeMux, marshaler grpcgw.Marshaler, writer http.ResponseWriter, request *http.Request, err error) {
    b, err := ioutil.ReadAll(req.Body)
    // b is empty

Sorry if I misreported it as a bug, I would appreciate some help.
Thanks a lot!

Expected behavior

I would expect to be able to read the request body.

Actual Behavior

I am not able to read the request body.

Your Environment

osx
go 1.21

Hi, thanks for your issue. Yeah this is unfortunate, but I don't know that there's much we can do here. As you say, the body has already been consumed in this case. Note that it shouldn't universally be the case that the body has been consumed, it's likely your specific use case. For example, here the body should still be available: https://github.com/grpc-ecosystem/grpc-gateway/blob/main/runtime/mux.go#L348. If you track down the case that you're hitting, it might be possible to add something that would buffer the request body, but in all honest you're best off doing this at the middleware level where you have access to the request before it's being handled by the gateway runtime.