website/pkg/utility/ip_address.go

30 lines
560 B
Go
Raw Normal View History

2023-06-24 22:39:45 +00:00
package utility
import (
2023-06-24 22:51:53 +00:00
"net"
2023-06-24 22:39:45 +00:00
"net/http"
"strings"
"code.nonshy.com/nonshy/website/pkg/config"
)
/*
IPAddress returns the best guess at the user's IP address, as a string for logging.
*/
func IPAddress(r *http.Request) string {
if config.Current.UseXForwardedFor {
if realIP := r.Header.Get("X-Real-IP"); realIP != "" {
return realIP
}
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
return strings.SplitN(xff, " ", 1)[0]
}
}
2023-06-24 22:51:53 +00:00
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
2023-06-24 22:39:45 +00:00
}