searcherside/infrastructure/api/middlewares/logging_middleware.go

39 lines
1.1 KiB
Go
Raw Normal View History

package middlewares
2024-06-06 20:08:51 +00:00
import (
"encoding/hex"
"hash/fnv"
"log/slog"
"net/http"
"strconv"
"time"
"code.icb4dc0.de/prskr/searcherside/infrastructure/logging"
2024-06-06 20:08:51 +00:00
)
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
requestLogger := logging.GetLogger(request.Context()).With(
slog.String("http.requestId", requestId(request)),
slog.String("http.method", request.Method),
slog.String("http.path", request.URL.Path),
)
requestLogger.Info("Handling incoming request")
next.ServeHTTP(writer, request.WithContext(logging.ContextWithLogger(request.Context(), requestLogger)))
requestLogger.Info("Handled incoming request")
})
}
func requestId(req *http.Request) string {
hash := fnv.New64()
_, _ = hash.Write([]byte(req.Method))
_, _ = hash.Write([]byte(req.RequestURI))
_, _ = hash.Write([]byte(req.RemoteAddr))
_, _ = hash.Write([]byte(req.UserAgent()))
_, _ = hash.Write(strconv.AppendInt(nil, time.Now().UTC().UnixNano(), 10))
return hex.EncodeToString(hash.Sum(nil))
}