refactors HTTP server initialization, improves logging middleware, and updates documentation #1

Merged
rmcguire merged 2 commits from fix-http-log-middleware into main 2025-08-24 15:50:36 +00:00
Showing only changes of commit ae11d4aa01 - Show all commits

View File

@@ -3,7 +3,8 @@ package http
import ( import (
"bytes" "bytes"
"context" "context"
"errors" "fmt"
"io"
"net/http" "net/http"
"regexp" "regexp"
"time" "time"
@@ -42,16 +43,30 @@ func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
Msg("http request served") Msg("http request served")
// Log response with body if not 204 // Log response with body if not 204
if lrr.statusCode != http.StatusNoContent { if lrr.statusCode == http.StatusNoContent {
trcLog := log.Trace(). trcLog := log.Trace().
Str("path", r.URL.Path). Str("path", r.URL.Path).
Int("statusCode", lrr.statusCode) Int("statusCode", lrr.statusCode)
trcLog.Msg("http response (no content)") // Explicitly log 204
return // No body to log for 204 No Content
}
trcLog := log.Trace().
Str("path", r.URL.Path).
Int("statusCode", lrr.statusCode)
firstByte, err := lrr.body.ReadByte() firstByte, err := lrr.body.ReadByte()
if err != nil { if err != nil {
trcLog.Err(errors.New("invalid response body")).Send() if err == io.EOF {
return // Body is empty, which might be valid for some non-204 responses.
trcLog.Msg("http response (empty body)")
} else {
// Other error reading the body. Wrap the original error for context.
trcLog.Err(fmt.Errorf("error reading response body: %w", err)).Send()
} }
lrr.body.UnreadByte() return // No further body processing if there was an error or it was empty
}
lrr.body.UnreadByte() // Put the byte back for Bytes() to read
if firstByte == '{' { if firstByte == '{' {
trcLog = trcLog.RawJSON("response", lrr.body.Bytes()) trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
@@ -59,7 +74,6 @@ func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
trcLog = trcLog.Bytes("response", lrr.body.Bytes()) trcLog = trcLog.Bytes("response", lrr.body.Bytes())
} }
trcLog.Msg("http response") trcLog.Msg("http response")
}
}) })
} }