From 926aa182d91c56fd2019a951dda71352a882b16d Mon Sep 17 00:00:00 2001 From: Randell Date: Sat, 8 Jun 2024 15:38:19 -0600 Subject: [PATCH] Try to get user's IP --- server/handler/handler.go | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/server/handler/handler.go b/server/handler/handler.go index 368180f..9e2928b 100644 --- a/server/handler/handler.go +++ b/server/handler/handler.go @@ -3,8 +3,10 @@ package handler import ( "context" "log/slog" + "net" "net/http" "strconv" + "strings" "github.com/Piszmog/pathwise/db" "github.com/a-h/templ" @@ -47,9 +49,19 @@ func getUserID(r *http.Request) (int64, error) { } func getClientIP(r *http.Request) string { - ip := r.Header.Get("X-FORWARD-FOR") - if ip != "" { - return ip + xff := r.Header.Get("X-Forwarded-For") + if xff != "" { + ip := strings.Split(xff, ",")[0] + ip = strings.TrimSpace(ip) + if net.ParseIP(ip) != nil { + return ip + } } - return r.RemoteAddr + + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + + return ip }