trixie/http.go
Elara6331 2b23f0caef
Some checks failed
ci/woodpecker/tag/manifest unknown status
ci/woodpecker/tag/build/1 Pipeline failed
ci/woodpecker/tag/build/2 Pipeline failed
Initial Commit
2025-05-16 16:39:55 +02:00

37 lines
855 B
Go

package main
import (
"net"
"net/http"
"strings"
)
// realIP is a middleware that extracts the real IP from the headers of
// an HTTP requests and modifies the request for the next handler.
func realIP(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ip := realIPFromHeaders(r); ip != "" {
r.RemoteAddr = net.JoinHostPort(ip, "0")
}
next.ServeHTTP(w, r)
})
}
// realIPFromHeaders extracts the real IP from the headers of an HTTP request
func realIPFromHeaders(r *http.Request) string {
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
parts := strings.Split(xff, ",")
if len(parts) > 0 {
ip := strings.TrimSpace(parts[0])
if ip != "" {
return ip
}
}
}
xrip := strings.TrimSpace(r.Header.Get("X-Real-IP"))
if xrip != "" {
return xrip
}
return ""
}