From 50bcb16c715c50860d8114c7893419c71eb17ae9 Mon Sep 17 00:00:00 2001
From: Nicolas Carlier <n.carlier@nunux.org>
Date: Sat, 9 Jul 2022 07:54:22 +0200
Subject: [PATCH] feat(): trace real IP

---
 pkg/middleware/logger.go | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/pkg/middleware/logger.go b/pkg/middleware/logger.go
index 757fe7a..9958e7d 100644
--- a/pkg/middleware/logger.go
+++ b/pkg/middleware/logger.go
@@ -25,13 +25,9 @@ func Logger(next http.Handler) http.Handler {
 			if !ok {
 				requestID = "0"
 			}
-			addr := r.RemoteAddr
-			if i := strings.LastIndex(addr, ":"); i != -1 {
-				addr = addr[:i]
-			}
 			logger.Info.Printf(
 				"%s - - [%s] %q %d %d %q %q %q",
-				addr,
+				getRequestIP(r),
 				start.Format("02/Jan/2006:15:04:05 -0700"),
 				fmt.Sprintf("%s %s %s", r.Method, r.URL, r.Proto),
 				o.status,
@@ -45,6 +41,21 @@ func Logger(next http.Handler) http.Handler {
 	})
 }
 
+func getRequestIP(r *http.Request) string {
+	ip := r.Header.Get("X-Forwarded-For")
+	if ip == "" {
+		ip = r.RemoteAddr
+	}
+	if comma := strings.Index(ip, ","); comma != -1 {
+		ip = ip[0:comma]
+	}
+	if colon := strings.LastIndex(ip, ":"); colon != -1 {
+		ip = ip[:colon]
+	}
+
+	return ip
+}
+
 type responseObserver struct {
 	http.ResponseWriter
 	status      int