import ( "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/pkg/conversion" ) // define the conversion function func secretToInternal(obj runtime.Object) (interface{}, error) { secret := obj.(*v1.Secret) // convert the secret to an internal Go representation return myInternal.Secret{Data: secret.Data}, nil } // create a default converter with the conversion function registered converter := conversion.NewConverter(func() interface{} { return &myInternal.Secret{} }, secretToInternal) // use the converter to convert a Kubernetes secret k8sSecret := &v1.Secret{Data: map[string][]byte{"key": []byte("value")}} internalSecret := &myInternal.Secret{} if err := converter.Convert(k8sSecret, internalSecret, nil); err != nil { // handle error }
import ( "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/pkg/api/v1" "k8s.io/client-go/pkg/conversion" ) // define the conversion function func internalToSvcAcctList(obj interface{}) (runtime.Object, error) { // convert the internal representation to a Kubernetes ServiceAccountList internalList := obj.([]*myInternal.ServiceAccount) svcAcctList := &v1.ServiceAccountList{} for _, internal := range internalList { svcAcct := &v1.ServiceAccount{ ObjectMeta: v1.ObjectMeta{Name: internal.Name}, Secrets: []v1.ObjectReference{}, } for _, secret := range internal.Secrets { svcAcct.Secrets = append(svcAcct.Secrets, v1.ObjectReference{ Name: secret.Name, Namespace: secret.Namespace, }) } svcAcctList.Items = append(svcAcctList.Items, *svcAcct) } return svcAcctList, nil } // create a scheme with the Kubernetes types registered scheme := runtime.NewScheme() corev1.AddToScheme(scheme) // register the conversion function with the scheme groupVersion := schema.GroupVersion{Group: "", Version: "v1"} scheme.AddConversionFuncs( internalToSvcAcctList, conversion.ChainFuncs( internalToSvcAcctList, conversion.ReverseConversionFunc(internalToSvcAcctList)), ) // create a default converter with the scheme converter := conversion.NewConverterForScheme(scheme) // use the converter to convert an internal Go representation internalList := []*myInternal.ServiceAccount{ {Name: "my-service-account", Secrets: []myInternal.SecretReference{ {Name: "my-secret", Namespace: "default"}, }}, } obj, err := converter.ToAPIVersions(groupVersion.WithKind("ServiceAccountList"), internalList, nil) if err != nil { // handle error } svcAcctList := obj.(*v1.ServiceAccountList)