Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'internal/request/request.go')
-rw-r--r--internal/request/request.go36
1 files changed, 36 insertions, 0 deletions
diff --git a/internal/request/request.go b/internal/request/request.go
index f98b0819..14ee612b 100644
--- a/internal/request/request.go
+++ b/internal/request/request.go
@@ -3,6 +3,7 @@ package request
import (
"net"
"net/http"
+ "net/netip"
)
const (
@@ -10,6 +11,8 @@ const (
SchemeHTTP = "http"
// SchemeHTTPS name for the HTTPS scheme
SchemeHTTPS = "https"
+ // IPV6PrefixLength is the length of the IPv6 prefix
+ IPV6PrefixLength = 64
)
// IsHTTPS checks whether the request originated from HTTP or HTTPS.
@@ -38,3 +41,36 @@ func GetRemoteAddrWithoutPort(r *http.Request) string {
return remoteAddr
}
+
+// GetIPV4orIPV6PrefixWithoutPort strips the port from the r.RemoteAddr
+// and returns IPV4 address or IPV6 Prefix.
+func GetIPV4orIPV6PrefixWithoutPort(r *http.Request) string {
+ return GetIPV4orIPV6Prefix(r.RemoteAddr)
+}
+
+// GetIPV4orIPV6Prefix returns either the full IPv4 address or the /64 prefix
+// of the IPv6 address from the provided remote address, without the port.
+// For IPv4 it returns the full address. For IPv6 it returns the /64 prefix.
+func GetIPV4orIPV6Prefix(remoteAddr string) string {
+ remoteIP, _, err := net.SplitHostPort(remoteAddr)
+ if err != nil {
+ remoteIP = remoteAddr
+ }
+
+ addr, err := netip.ParseAddr(remoteIP)
+ if err != nil {
+ return remoteIP
+ }
+
+ if addr.Is4() {
+ return remoteIP
+ } else if addr.Is6() {
+ ipv6Prefix, err := addr.Prefix(IPV6PrefixLength)
+ if err != nil {
+ return remoteIP
+ }
+ return ipv6Prefix.String()
+ }
+
+ return remoteIP
+}