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
- In the
NewServeMux
function, pass aWithErrorHandler
custom error handler function
return grpcgw.NewServeMux(
...
grpcgw.WithErrorHandler(customErrorHandler(logger)),
)
- 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.