Home > OS >  Refactor golang function - what type should be used?
Refactor golang function - what type should be used?

Time:11-08

Could anyone of you tell how to refactor the following functions, please?

I'd like to have one function eg. getResource(name string, resourceType ????) []v1.?????, but don't know what would be its return type.

func getPods(name string) []v1.Pod {
    pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), getListOption(name))

    if err != nil {
        panic(err.Error())
    }
    return pods.Items
}

func getServices(name string) []v1.Service {
    services, err := clientset.CoreV1().Services(namespace).List(context.TODO(), getListOption(name))

    if err != nil {
        panic(err.Error())
    }
    return services.Items
}

CodePudding user response:

While the invocation is nearly identical, and the content is nearly identical, they types are different. CoreV1().Pods(namespace).List is :

List(ctx context.Context, opts metav1.ListOptions) (*v1.PodList, error)

but CoreV1().Services(namespace).List is

List(ctx context.Context, opts metav1.ListOptions) (*v1.ServiceList, error)

One returns a *v1.PodList and the other returns a *v1.ServiceList. Both these distinct objects have Items, but one is a []*Service and the other is a []*Pod.

I personally would think about not wrapping either. I would call the underlying functions instead, using the same CoreV1 client in both cases. I certainly wouldn't try to combine them into one function.

If there's something to be combined here, it's namespace and name:

type ByName struct {
   Name string
   Namespace string
   v1 corev1.CoreV1Interface
}

func (b *ByName)Services(ctx context.Context) []v1.Service , error {
   return b.v1.Services(namespace).List(ctx,  getListOption(b.Name))
}

func (b *ByName)Pods(ctx context.Context) []v1.Pod, error {
  return b.v1.Pods(b.Namespace).List(ctx, getListOption(b.Name))
}

Now you don't have to pass name and namespace:

b := &ByName{
  Name: name,
  Namespace: namespace,
  v1: clientset.CoreV1(),
}

if svcs, err :=  b.Services(); err != nil {
   return nil, err
} else if pods, err := b.Pods(); err != nil {
  return nil, err
} else {
  ... continue processing
}

And you get the brevity you want without having to do a bunch of type checking.

  • Related