From 631adc6b56597e09bb0d65d0aa1d343eb2379165 Mon Sep 17 00:00:00 2001 From: HeshamTB Date: Mon, 2 Oct 2023 21:50:07 +0300 Subject: [PATCH] fix: Log real ip if X-RealIP is set --- logging.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/logging.go b/logging.go index b4248e4..09c94bc 100644 --- a/logging.go +++ b/logging.go @@ -18,7 +18,7 @@ func (l *LoggingHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { l.Handler.ServeHTTP(w, r) log.Println( - fmt.Sprintf("%s %s %s %v", r.RemoteAddr, r.Method, r.URL.Path, time.Since(t1)), + fmt.Sprintf("%s %s %s %v", getIP(r), r.Method, r.URL.Path, time.Since(t1)), ) } @@ -26,3 +26,12 @@ func (l *LoggingHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func NewLogger(handler http.Handler) LoggingHTTPHandler { return LoggingHTTPHandler{handler} } + +func getIP(r *http.Request) string { + + RealIP := r.Header.Get("X-Real-IP") + if RealIP == "" { + return r.RemoteAddr + } + return RealIP +}