real-ip-request-printer/main.go

55 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-11-08 17:23:44 +03:00
package main
import (
"fmt"
"net/http"
"os"
"strings"
)
func getClientIP(r *http.Request) string {
// Check common headers for real client IP
if ip := r.Header.Get("X-Real-Ip"); ip != "" {
return ip
}
if forwardedFor := r.Header.Get("X-Forwarded-For"); forwardedFor != "" {
ips := strings.Split(forwardedFor, ",")
return strings.TrimSpace(ips[0])
}
// Fallback to remote address
return r.RemoteAddr
}
func handler(w http.ResponseWriter, r *http.Request) {
// Set content type
w.Header().Set("Content-Type", "text/plain")
// Get client IP
clientIP := getClientIP(r)
// Write response
fmt.Fprintf(w, "Request IP: %s\n", clientIP)
fmt.Fprintln(w, "Headers:")
for name, values := range r.Header {
for _, value := range values {
fmt.Fprintf(w, "%s: %s\n", name, value)
}
}
}
func main() {
// Get the listen address from the environment variable or use default
listenAddr := os.Getenv("LISTEN")
if listenAddr == "" {
listenAddr = "0.0.0.0:8080"
}
http.HandleFunc("/", handler)
fmt.Printf("Starting server on %s\n", listenAddr)
if err := http.ListenAndServe(listenAddr, nil); err != nil {
fmt.Printf("Error starting server: %s\n", err)
}
}