Sign In

Curriculum 30: Kubectl Internals

Client-Go Library

25 min · 50 XP

client-go Library

client-go is the official Go client library for Kubernetes. It powers kubectl itself and is the foundation for building controllers, operators, and any Go program that interacts with Kubernetes.

Core Components

The library provides typed clients for every built-in Kubernetes resource:

import (
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
)

// Build a client from kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
clientset, err := kubernetes.NewForConfig(config)

// List pods in a namespace
pods, err := clientset.CoreV1().Pods("production").List(
    context.TODO(), metav1.ListOptions{},
)

Informers

Informers are the backbone of efficient Kubernetes controllers. They watch the API server and maintain a local cache:

factory := informers.NewSharedInformerFactory(clientset, 30*time.Second)
podInformer := factory.Core().V1().Pods().Informer()

// Register event handlers
podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
    AddFunc: func(obj interface{}) {
        pod := obj.(*v1.Pod)
        fmt.Printf("Pod added: %s\n", pod.Name)
    },
    UpdateFunc: func(old, new interface{}) { /* handle updates */ },
    DeleteFunc: func(obj interface{}) { /* handle deletions */ },
})

factory.Start(stopCh)
factory.WaitForCacheSync(stopCh)

Listers

Listers read from the informer cache, avoiding API server calls entirely:

podLister := factory.Core().V1().Pods().Lister()

// Read from local cache (no API call)
pod, err := podLister.Pods("production").Get("myapp")
pods, err := podLister.Pods("production").List(labels.Everything())

Work Queues

Controllers use rate-limited work queues to process events:

queue := workqueue.NewRateLimitingQueue(
    workqueue.DefaultControllerRateLimiter(),
)

// Enqueue an item
queue.Add(key)

// Process items
key, shutdown := queue.Get()
defer queue.Done(key)
// Process key, then call queue.Forget(key) on success

Together, informers, listers, and work queues form the standard controller pattern used throughout the Kubernetes ecosystem.