package middlewares import ( "encoding/hex" "hash/fnv" "log/slog" "net/http" "strconv" "time" "code.icb4dc0.de/prskr/searcherside/infrastructure/logging" ) 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)) }