Adjust to new K8s 1.30 API

This commit is contained in:
Joshua Casey
2024-04-19 18:03:37 -05:00
committed by Ryan Richard
parent 581f671643
commit 9c2df74e54
10 changed files with 78 additions and 132 deletions

View File

@@ -12,6 +12,7 @@ import (
"strings"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
)
type HostPort struct {
@@ -41,7 +42,7 @@ func (h *HostPort) Endpoint() string {
// - "[<IPv6>]:<port>" (IPv6 address with port, brackets are required)
//
// If the input does not specify a port number, then defaultPort will be used.
func Parse(endpoint string, defaultPort uint16) (HostPort, error) {
func Parse(endpoint string, defaultPort uint16, paths ...string) (HostPort, error) {
// Try parsing it both with and without an implicit port 443 at the end.
host, port, err := net.SplitHostPort(endpoint)
@@ -61,9 +62,13 @@ func Parse(endpoint string, defaultPort uint16) (HostPort, error) {
return HostPort{}, fmt.Errorf("invalid port %q", port)
}
if len(paths) < 1 {
paths = []string{"UNKNOWN_PATH"}
}
// Check if the host part is a IPv4 or IPv6 address or a valid hostname according to RFC 1123.
switch {
case len(validation.IsValidIP(host)) == 0:
case len(validation.IsValidIP(field.NewPath(paths[0], paths[1:]...), host)) == 0:
case len(validation.IsDNS1123Subdomain(host)) == 0:
default:
return HostPort{}, fmt.Errorf("host %q is not a valid hostname or IP address", host)

View File

@@ -17,6 +17,7 @@ func TestParse(t *testing.T) {
name string
input string
defaultPort uint16
paths []string
expectErr string
expect HostPort
expectEndpoint string
@@ -42,6 +43,13 @@ func TestParse(t *testing.T) {
expect: HostPort{Host: "127.0.0.1", Port: 8443},
expectEndpoint: "127.0.0.1:8443",
},
{
name: "invalid IPv4",
input: "1.1.1.",
defaultPort: 443,
paths: []string{"does", "not", "matter", "because", "this", "error", "is", "ignored"},
expectErr: `host "1.1.1." is not a valid hostname or IP address`,
},
{
name: "IPv4 as IPv6 in brackets with port",
input: "[::127.0.0.1]:8443",
@@ -170,7 +178,7 @@ func TestParse(t *testing.T) {
} {
tt := tt
t.Run(tt.name, func(t *testing.T) {
got, err := Parse(tt.input, tt.defaultPort)
got, err := Parse(tt.input, tt.defaultPort, tt.paths...)
if tt.expectErr == "" {
assert.NoError(t, err)
assert.Equal(t, tt.expect, got)