ip.go

17 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package security

import (
	"net/http"
	"strings"
)

// ClientIP extracts the client IP from a request, respecting X-Forwarded-For.
func ClientIP(r *http.Request) string {
	if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
		if i := strings.IndexByte(fwd, ','); i > 0 {
			return strings.TrimSpace(fwd[:i])
		}
		return fwd
	}
	return r.RemoteAddr
}