From f4b529eb7fb1a36c6f592919f54c6a9633420ac3 Mon Sep 17 00:00:00 2001 From: skidoodle Date: Thu, 13 Jun 2024 12:34:13 +0200 Subject: [PATCH] chore: Refactor IP address retrieval logic in main.go --- main.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/main.go b/main.go index caf1eb5..12f1219 100644 --- a/main.go +++ b/main.go @@ -187,14 +187,15 @@ func handler(w http.ResponseWriter, r *http.Request) { IPAddress = requestedThings[1] } - if IPAddress == "" || IPAddress == "self" { - if realIP, ok := r.Header["X-Forwarded-For"]; ok && len(realIP) > 0 { - IPAddress = realIP[0] - } else { - IPAddress = extractIP(r.RemoteAddr) - } - } - + if IPAddress == "" || IPAddress == "self" { + if realIP := r.Header.Get("CF-Connecting-IP"); realIP != "" { + IPAddress = realIP + } else if realIP := r.Header.Get("X-Forwarded-For"); realIP != "" { + IPAddress = strings.Split(realIP, ",")[0] + } else { + IPAddress = extractIP(r.RemoteAddr) + } + } ip := net.ParseIP(IPAddress) if ip == nil { w.Header().Set("Content-Type", "text/plain; charset=utf-8")