Skip to content

Commit

Permalink
fix: empty body while logging (#67)
Browse files Browse the repository at this point in the history
* fix: empty body while logging

- body was read while processing the request
- made a copy of the body buffer, to log later

* refactor: use io.Copy

* fix: use io.Readall

* fix: return if body reading fails

* fix: change log type to error
  • Loading branch information
ishanarya0 authored Sep 21, 2023
1 parent 2c4ef1f commit 4fdfd50
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions internal/server/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ func requestLogger(lg *zap.Logger) gorillamux.MiddlewareFunc {
Status: http.StatusOK,
ResponseWriter: wr,
}

bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
lg.Error("error reading request body: %v", zap.String("error", err.Error()))
return
}
reader := io.NopCloser(bytes.NewBuffer(bodyBytes))
req.Body = reader

next.ServeHTTP(wrapped, req)

if req.URL.Path == "/ping" {
Expand All @@ -109,25 +118,14 @@ func requestLogger(lg *zap.Logger) gorillamux.MiddlewareFunc {
zap.Int("status", wrapped.Status),
}

switch req.Method {
case http.MethodGet:
break
default:
buf, err := io.ReadAll(req.Body)
if len(bodyBytes) > 0 {
dst := bytes.NewBuffer(nil)
err = json.Compact(dst, bodyBytes)
if err != nil {
lg.Debug("error reading request body: %v", zap.String("error", err.Error()))
} else if len(buf) > 0 {
dst := &bytes.Buffer{}
err := json.Compact(dst, buf)
if err != nil {
lg.Debug("error json compacting request body: %v", zap.String("error", err.Error()))
} else {
fields = append(fields, zap.String("request_body", dst.String()))
}
lg.Error("error json compacting request body: %v", zap.String("error", err.Error()))
} else {
fields = append(fields, zap.String("request_body", dst.String()))
}

reader := io.NopCloser(bytes.NewBuffer(buf))
req.Body = reader
}

if !is2xx(wrapped.Status) {
Expand Down

0 comments on commit 4fdfd50

Please sign in to comment.