2024-06-19 19:19:37 +00:00
|
|
|
package middlewares
|
2024-06-06 20:08:51 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/hex"
|
|
|
|
"hash/fnv"
|
|
|
|
"log/slog"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
2024-06-19 19:19:37 +00:00
|
|
|
"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))
|
|
|
|
}
|