logRequestBody logs the request body when the response status code is not 200. This addresses the issue of being unable to retrieve the request body in the customErrorHandler middleware.
(h http.Handler)
| 95 | // logRequestBody logs the request body when the response status code is not 200. |
| 96 | // This addresses the issue of being unable to retrieve the request body in the customErrorHandler middleware. |
| 97 | func logRequestBody(h http.Handler) http.Handler { |
| 98 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 99 | lw := newLogResponseWriter(w) |
| 100 | body, err := io.ReadAll(r.Body) |
| 101 | if err != nil { |
| 102 | http.Error(w, fmt.Sprintf("grpc server read request body err %+v", err), http.StatusBadRequest) |
| 103 | return |
| 104 | } |
| 105 | clonedR := r.Clone(r.Context()) |
| 106 | clonedR.Body = io.NopCloser(bytes.NewReader(body)) |
| 107 | |
| 108 | h.ServeHTTP(lw, clonedR) |
| 109 | |
| 110 | if lw.statusCode != http.StatusOK { |
| 111 | grpclog.Errorf("http error %+v request body %+v", lw.statusCode, string(body)) |
| 112 | } |
| 113 | }) |
| 114 | } |
no test coverage detected