Dagang Wei
Dagang Wei

Reputation: 26548

How do I convert runtime.Object to a specific type?

I'm writing a custom controller with Kubebuilder framework, in one method, I got an object of type runtime.Object, I know I should be able to convert it to the specific type say MyCustomResource, but I cannot figure out how from the doc.

Upvotes: 4

Views: 5879

Answers (1)

erstaples
erstaples

Reputation: 2076

It should be as easy as this:

func convertToMyCustomResource(obj runtime.Object) *v1alpha1.MyCustomResource {
  myobj := obj.(*v1alpha1.MyCustomResource)
  return myobj
}

If this produces an error (e.g. Impossible type assertion), make sure MyCustomResource satisfies the runtime.Object interface; i.e.

  1. Run the controller-gen tool to generate the DeepCopyObject method

    go run vendor/sigs.k8s.io/controller-tools/cmd/controller-gen/main.go paths=./api/... object
    
  2. Add the "k8s.io/apimachinery/pkg/apis/meta/v1".TypeMeta field to the MyCustomResource struct, which implements the GetObjectKind method.

    import (
      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    )

    type MyCustomResource struct {
      metav1.TypeMeta `json:",inline"`
      // ... other stuff
    }

Upvotes: 7

Related Questions