Browse Source

add source ip into middleware/logging.go

Virgil Ollivier 5 tháng trước cách đây
mục cha
commit
acecc9825e
2 tập tin đã thay đổi với 20 bổ sung5 xóa
  1. 7 3
      main.go
  2. 13 2
      middleware/logging.go

+ 7 - 3
main.go

@@ -10,16 +10,20 @@ import (
 )
 
 func main() {
-	// Initialize OVH client
+	// Initialize the OVH client configuration for API interactions
 	config.InitOVHClient()
 
+	// Create a new Gorilla Mux router instance for handling HTTP requests
 	r := mux.NewRouter()
 
-	// Setup routes
+	// Configure all application routes and their handlers
 	routes.SetupRoutes(r)
+	log.Println("Routes configured...")
 
-	// Start server
+	// Start the HTTP server on port 8080
+	// Log server startup message
 	log.Println("Server starting on port 8080...")
+	// Listen and serve HTTP requests, log fatal error if server fails to start
 	if err := http.ListenAndServe(":8080", r); err != nil {
 		log.Fatal(err)
 	}

+ 13 - 2
middleware/logging.go

@@ -3,6 +3,7 @@ package middleware
 import (
 	"log"
 	"net/http"
+	"strings"
 	"time"
 )
 
@@ -11,10 +12,20 @@ func LoggingMiddleware(next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		start := time.Now()
 
-		log.Printf("Started %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
+		// 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 in %v", r.Method, r.URL.Path, time.Since(start))
+		log.Printf("Completed %s %s from %s (source IP: %s) in %v", r.Method, r.URL.Path, r.RemoteAddr, sourceIP, time.Since(start))
 	})
 }