Skip to content

Instantly share code, notes, and snippets.

@jpeach
Created January 10, 2022 04:41
Show Gist options
  • Save jpeach/67dc3a073bea39075641eb0c6259b133 to your computer and use it in GitHub Desktop.
Save jpeach/67dc3a073bea39075641eb0c6259b133 to your computer and use it in GitHub Desktop.
names API for reference types
package reference
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/gateway-api/apis/v1alpha2"
)
// NamespaceOf returns the namespace of the Gateway API object reference given by ref.
//
// ref must be of type *v1alpha2.ParentRef, *v1alpha2.LocalObjectReference,
// *v1alpha2.SecretObjectReference or *v1alpha2.BackendObjectReference.
func NamespaceOf(parent metav1.Object, ref interface{}) string {
switch ref := ref.(type) {
case *v1alpha2.LocalObjectReference:
return parent.GetNamespace()
case *v1alpha2.ParentRef,
*v1alpha2.SecretObjectReference,
*v1alpha2.BackendObjectReference:
// Namespace is the namespace of the backend. When unspecified, the local
// namespace is inferred.
if ref.Namespace != nil && ref.Namespace != "" {
return ref.Namespace
}
return parent.GetNamespace()
default:
panic(fmt.Sprintf("%T is not a Gateway API object reference type", ref))
}
}
// NameOf returns the name of the Gateway API object reference given by ref.
//
// ref must be of type *v1alpha2.ParentRef, *v1alpha2.LocalObjectReference,
// *v1alpha2.SecretObjectReference or *v1alpha2.BackendObjectReference.
func NameOf(ref interface{}) string {
switch ref := ref.(type) {
case *v1alpha2.ParentRef,
*v1alpha2.LocalObjectReference,
*v1alpha2.SecretObjectReference,
*v1alpha2.BackendObjectReference:
return ref.Name
default:
panic(fmt.Sprintf("%T is not a Gateway API object reference type", ref))
}
}
// NamespacedName returns the fully qualified object name of ref.
//
// ref must be of type *v1alpha2.ParentRef, *v1alpha2.LocalObjectReference,
// *v1alpha2.SecretObjectReference or *v1alpha2.BackendObjectReference.
func NamespacedName(parent metav1.Object, ref interface{}) types.NamespacedName {
return types.NamespacedName{
Namespace: NamespaceOf(parent, ref),
Name: NameOf(ref),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment