move helper funcs

This commit is contained in:
techknowlogick committed 2025-04-10 14:52:11 -04:00
1 parent 2a49d34521
commit 03af3b88c4
5 files changed
+118 -45

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package util
import (
"strings"
)
// TrimPortFromIP removes the client port from an IP address
// Handles both IPv4 and IPv6 addresses with ports
func TrimPortFromIP(ip string) string {
// Handle IPv6 with brackets: [IPv6]:port
if strings.HasPrefix(ip, "[") {
// If there's no port, return as is
if !strings.Contains(ip, "]:") {
return ip
}
// Remove the port part after ]:
return strings.Split(ip, "]:")[0] + "]"
}
// Count colons to differentiate between IPv4 and IPv6
colonCount := strings.Count(ip, ":")
// Handle IPv4 with port (single colon)
if colonCount == 1 {
return strings.Split(ip, ":")[0]
}
return ip
}
+66
View File
@@ -0,0 +1,66 @@
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTrimPortFromIP(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "IPv4 without port",
input: "192.168.1.1",
expected: "192.168.1.1",
},
{
name: "IPv4 with port",
input: "192.168.1.1:8080",
expected: "192.168.1.1",
},
{
name: "IPv6 without port",
input: "2001:db8::1",
expected: "2001:db8::1",
},
{
name: "IPv6 with brackets, without port",
input: "[2001:db8::1]",
expected: "[2001:db8::1]",
},
{
name: "IPv6 with brackets and port",
input: "[2001:db8::1]:8080",
expected: "[2001:db8::1]",
},
{
name: "localhost with port",
input: "localhost:8080",
expected: "localhost",
},
{
name: "Empty string",
input: "",
expected: "",
},
{
name: "Not an IP address",
input: "abc123",
expected: "abc123",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := TrimPortFromIP(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}