diff --git a/main.go b/main.go index b83ba4c..5e93e03 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "log" "net/http" "net/netip" @@ -55,17 +56,20 @@ func handleRoot(w http.ResponseWriter, r *http.Request) { } log.Printf("Type: %v\n", Type) - ip := determineRealIP(r) + ip, err := determineRealIP(r) + if err != nil { + log.Println(err.Error()) + w.WriteHeader(http.StatusInternalServerError) + } - w.WriteHeader(http.StatusOK) - err := writeFormattedIP(w, Type, ip) + err = writeFormattedIP(w, Type, ip) if err != nil { log.Println(err.Error()) w.WriteHeader(http.StatusInternalServerError) } } -func determineRealIP(r *http.Request) string { +func determineRealIP(r *http.Request) (string, error) { ip := r.RemoteAddr xRealIP := r.Header.Get("X-Real-IP") @@ -75,21 +79,17 @@ func determineRealIP(r *http.Request) string { ipPort, err := netip.ParseAddrPort(ip) if err != nil { - log.Println("Error while parsing AddrPort:", err.Error()) + return "", err } - ipAddrPort := ipPort.Addr().String() - if ipAddrPort == "invalid IP" { - ipAddr, err := netip.ParseAddr(ip) - if err != nil { - // Last resort - log.Println("Error while parsing Addr:", err.Error()) - return ip - } - ip = ipAddr.String() + + if !ipPort.IsValid() { + return "", errors.New("Zero IP") } - return ip + ip = ipPort.Addr().String() + + return ip, nil } func writeFormattedIP(w http.ResponseWriter, Type ResponseType, ip string) error { @@ -116,4 +116,3 @@ func writeFormattedIP(w http.ResponseWriter, Type ResponseType, ip string) erro return nil } -