From 8a111c128f7df5550ec4c70ddd86dca115f5aaaf Mon Sep 17 00:00:00 2001 From: yuriy0803 <68668177+yuriy0803@users.noreply.github.com> Date: Sun, 25 Feb 2024 18:50:58 +0100 Subject: [PATCH] Update server.go Add middleware to log the real client IP address Add middleware to log the real client IP address --- api/server.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/api/server.go b/api/server.go index 9324b7b..af35068 100644 --- a/api/server.go +++ b/api/server.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "log" + "net" "net/http" "sort" "strconv" @@ -244,6 +245,19 @@ func (s *ApiServer) collectshareCharts(login string, workerOnline int64) { func (s *ApiServer) listen() { r := mux.NewRouter() + // Add middleware to log the real client IP address + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Get the real client IP address using the getClientIP function + clientIP := getClientIP(r) + + // Log the request details including IP address, method, and path + log.Printf("[Diagnostics] Request from IP: %s - Method: %s, Path: %s", clientIP, r.Method, r.URL.Path) + + // Call the next handler in the middleware chain + next.ServeHTTP(w, r) + }) + }) r.HandleFunc("/api/finders", s.FindersIndex) r.HandleFunc("/api/stats", s.StatsIndex) r.HandleFunc("/api/miners", s.MinersIndex) @@ -258,6 +272,26 @@ func (s *ApiServer) listen() { } } +// getClientIP returns the real client IP address from the http.Request object +func getClientIP(r *http.Request) string { + // Try to use the "X-Forwarded-For" header, if available + forwardedFor := r.Header.Get("X-Forwarded-For") + if forwardedFor != "" { + // Extract the first IP address from the list (if multiple are present) + return strings.TrimSpace(strings.Split(forwardedFor, ",")[0]) + } + + // Try to use the "X-Real-IP" header, if available + realIP := r.Header.Get("X-Real-IP") + if realIP != "" { + return realIP + } + + // If neither X-Forwarded-For nor X-Real-IP is set, use the remote address + ip, _, _ := net.SplitHostPort(r.RemoteAddr) + return ip +} + func notFound(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Header().Set("Access-Control-Allow-Origin", "*")