main.go (864B)
1 package main 2 3 import ( 4 "fmt" 5 "net" 6 "net/http" 7 "net/http/cgi" 8 "strings" 9 ) 10 11 func handleRequest(w http.ResponseWriter, r *http.Request) { 12 envVal := r.Header.Get("X-Forwarded-For") 13 if envVal == "" { 14 http.Error(w, "Missing Header", http.StatusBadRequest) 15 return 16 } 17 18 remoteIP := envVal 19 if comma := strings.Index(envVal, ","); comma != -1 { 20 remoteIP = envVal[:comma] 21 } 22 remoteIP = strings.TrimSpace(remoteIP) 23 24 if parsedIP := net.ParseIP(remoteIP); parsedIP == nil { 25 w.Header().Set("Content-Type", "text/plain; charset=utf-8") 26 w.WriteHeader(http.StatusBadRequest) 27 fmt.Fprintf(w, "Invalid IP: %s", remoteIP) 28 return 29 } 30 31 w.Header().Set("Content-Type", "text/html; charset=utf-8") 32 w.WriteHeader(http.StatusOK) 33 fmt.Fprint(w, remoteIP) 34 } 35 36 func main() { 37 pledge() 38 39 if err := cgi.Serve(http.HandlerFunc(handleRequest)); err != nil { 40 panic(err) 41 } 42 }