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

This commit is contained in:
2025-08-24 11:46:17 -04:00
parent 92e78f533a
commit a972953040
2 changed files with 23 additions and 20 deletions

View File

@@ -1,3 +1,6 @@
// Package http provides functionality for setting up and managing HTTP servers.
// It includes features for health checks, Prometheus metrics, OpenTelemetry
// tracing, and custom middleware integration.
package http package http
import ( import (
@@ -133,8 +136,8 @@ func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
} }
} }
// Returns a shutdown func and a done channel if the // InitHTTPServer returns a shutdown func and a done channel if the
// server aborts abnormally. Returns error on failure to start // server aborts abnormally. Returns error on failure to start.
func InitHTTPServer(opts *opts.AppHTTP) ( func InitHTTPServer(opts *opts.AppHTTP) (
func(context.Context) error, <-chan any, error, func(context.Context) error, <-chan any, error,
) { ) {

View File

@@ -41,29 +41,29 @@ func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
Dur("duration", time.Since(start)). Dur("duration", time.Since(start)).
Msg("http request served") Msg("http request served")
// Log response body // Log response with body if not 204
trcLog := log.Trace(). if lrr.statusCode != http.StatusNoContent {
Str("path", r.URL.Path). trcLog := log.Trace().
Int("statusCode", lrr.statusCode) Str("path", r.URL.Path).
Int("statusCode", lrr.statusCode)
firstByte, err := lrr.body.ReadByte()
if err != nil {
trcLog.Err(errors.New("invalid response body")).Send()
return
}
lrr.body.UnreadByte()
// Check if it's JSON if firstByte == '{' {
firstByte, err := lrr.body.ReadByte() trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
if err != nil { } else {
trcLog.Err(errors.New("invalid response body")).Send() trcLog = trcLog.Bytes("response", lrr.body.Bytes())
return }
trcLog.Msg("http response")
} }
lrr.body.UnreadByte()
if firstByte == '{' {
trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
} else {
trcLog = trcLog.Bytes("response", lrr.body.Bytes())
}
trcLog.Msg("response payload")
}) })
} }
// Implement Flush to support the http.Flusher interface // Flush implements the http.Flusher interface to allow flushing buffered data.
func (w *LoggingResponseWriter) Flush() { func (w *LoggingResponseWriter) Flush() {
if flusher, ok := w.ResponseWriter.(http.Flusher); ok { if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush() flusher.Flush()