From 9f573a19d698114e0ac63bd9f394f181a3f9293a Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Tue, 3 Apr 2018 21:51:39 +0200 Subject: [PATCH] Add proxy IP detection Signed-off-by: Knut Ahlers --- http/logHandler.go | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/http/logHandler.go b/http/logHandler.go index 7a55372..95b7bc6 100644 --- a/http/logHandler.go +++ b/http/logHandler.go @@ -3,17 +3,22 @@ package http import ( "log" "net/http" + "strings" "time" "github.com/Luzifer/go_helpers/accessLogger" ) type HTTPLogHandler struct { - Handler http.Handler + Handler http.Handler + TrustedIPHeaders []string } func NewHTTPLogHandler(h http.Handler) http.Handler { - return HTTPLogHandler{Handler: h} + return HTTPLogHandler{ + Handler: h, + TrustedIPHeaders: []string{"X-Forwarded-For", "RemoteAddr", "X-Real-IP"}, + } } func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) { @@ -23,7 +28,7 @@ func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) { l.Handler.ServeHTTP(ares, r) log.Printf("%s - \"%s %s\" %d %d \"%s\" \"%s\" %s", - r.RemoteAddr, + l.findIP(r), r.Method, r.URL.Path, ares.StatusCode, @@ -33,3 +38,15 @@ func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) { time.Since(start), ) } + +func (l HTTPLogHandler) findIP(r *http.Request) string { + remoteAddr := strings.SplitN(r.RemoteAddr, ":", 2)[0] + + for _, hdr := range l.TrustedIPHeaders { + if value := r.Header.Get(hdr); value != "" { + return strings.SplitN(value, ",", 2)[0] + } + } + + return remoteAddr +}