From 8d38a86f86636b9dcdf4c72b1850e3a75168eb72 Mon Sep 17 00:00:00 2001 From: LandaMm Date: Wed, 11 Jun 2025 20:35:38 +0200 Subject: [PATCH] feat: get client ip util --- internal/util/location.go | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/internal/util/location.go b/internal/util/location.go index 297e271..1b005ad 100644 --- a/internal/util/location.go +++ b/internal/util/location.go @@ -2,7 +2,10 @@ package util import ( "encoding/json" + "log" + "net" "net/http" + "strings" ) type LocationResult struct { @@ -14,7 +17,7 @@ type LocationResult struct { func GetLocation(ip string) (LocationResult, error) { var loc LocationResult // Example using ipinfo.io free API - resp, err := http.Get("https://ipinfo.io/" + ip + "/json") + resp, err := http.Get("http://ip-api.com/json/" + ip + "?fields=25") if err != nil { return loc, err } @@ -22,3 +25,22 @@ func GetLocation(ip string) (LocationResult, error) { json.NewDecoder(resp.Body).Decode(&loc) return loc, nil } + +func GetClientIP(r *http.Request) string { + // This header will be set by ngrok to the original client IP + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + log.Printf("DEBUG: Getting IP from X-Forwarded-For: %s\n", xff) + // X-Forwarded-For: client, proxy1, proxy2, ... + ips := strings.Split(xff, ",") + if len(ips) > 0 { + return strings.TrimSpace(ips[0]) + } + } + // Fallback to RemoteAddr (not the real client IP, but just in case) + host, _, err := net.SplitHostPort(r.RemoteAddr) + log.Printf("DEBUG: Falling to request remote addr: %s (%s)\n", host, r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +}