37 lines
855 B
Go
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 ""
|
|
} |