fix: remove port from response

This commit is contained in:
HeshamTB 2024-04-04 00:49:07 +03:00
parent 992239ff1f
commit fc458f1cda

31
main.go
View File

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