package middleware import ( "log" "net/http" "strings" "time" ) // LoggingMiddleware logs information about each HTTP request func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() // Get the real IP address sourceIP := r.Header.Get("X-Forwarded-For") if sourceIP == "" { sourceIP = r.RemoteAddr } // If we got multiple IPs in X-Forwarded-For, take the first one if strings.Contains(sourceIP, ",") { sourceIP = strings.Split(sourceIP, ",")[0] } log.Printf("Started %s %s from %s (source IP: %s)", r.Method, r.URL.Path, r.RemoteAddr, sourceIP) next.ServeHTTP(w, r) log.Printf("Completed %s %s from %s (source IP: %s) in %v", r.Method, r.URL.Path, r.RemoteAddr, sourceIP, time.Since(start)) }) }