CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-k8s-io--client-go

Official Go client library for Kubernetes API - typed clients, controllers, and cluster interaction tools

Overview
Eval results
Files

rest-client.mddocs/reference/

REST Client and Configuration

Back to Index

The REST package provides the foundation for all Kubernetes client communication, including configuration, authentication, transport, and low-level HTTP operations.

Package Information

  • Package: k8s.io/client-go/rest
  • Config Loading: k8s.io/client-go/tools/clientcmd
  • Transport: k8s.io/client-go/transport

Core Imports

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

Configuration

rest.Config Structure

type Config struct {
    // Host must be a host string, a host:port pair, or a URL to the base of the apiserver
    Host string

    // APIPath is a sub-path that points to an API root
    APIPath string

    // ContentConfig contains settings that affect how objects are transformed
    ContentConfig

    // Server authentication
    Username string
    Password string `datapolicy:"password"`

    // Bearer token authentication
    BearerToken string `datapolicy:"token"`
    BearerTokenFile string

    // Impersonation
    Impersonate ImpersonationConfig

    // Plugin-specified authentication
    AuthProvider *clientcmdapi.AuthProviderConfig
    AuthConfigPersister AuthProviderConfigPersister
    ExecProvider *clientcmdapi.ExecConfig

    // TLS configuration
    TLSClientConfig

    // User agent
    UserAgent string

    // DisableCompression bypasses automatic GZip compression
    DisableCompression bool

    // Transport customization
    Transport http.RoundTripper
    WrapTransport transport.WrapperFunc

    // Rate limiting
    QPS float32        // Queries per second (default: 5.0)
    Burst int          // Burst allowance (default: 10)
    RateLimiter flowcontrol.RateLimiter

    // Warning handlers
    WarningHandler WarningHandler
    WarningHandlerWithContext WarningHandlerWithContext

    // Timeout
    Timeout time.Duration

    // Dial function
    Dial func(ctx context.Context, network, address string) (net.Conn, error)

    // Proxy function
    Proxy func(*http.Request) (*url.URL, error)
}

// Default rate limiting constants
const (
    DefaultQPS   float32 = 5.0
    DefaultBurst int     = 10
)

TLS Configuration

type TLSClientConfig struct {
    // Server certificate validation
    Insecure bool
    ServerName string

    // Certificate data (preferred over file paths)
    CertData []byte
    KeyData  []byte `datapolicy:"security-key"`
    CAData   []byte

    // Certificate files
    CertFile string
    KeyFile  string
    CAFile   string

    // Function to retrieve client certificate
    GetCert func() (*tls.Certificate, error)

    // NextProtos for ALPN
    NextProtos []string
}

Impersonation

type ImpersonationConfig struct {
    UserName string                 // Username to impersonate
    UID string                      // UID to impersonate
    Groups []string                 // Groups to impersonate
    Extra map[string][]string       // Extra fields
}

Creating Configuration

In-Cluster Configuration

// For applications running inside a Kubernetes pod
config, err := rest.InClusterConfig()
if err != nil {
    if err == rest.ErrNotInCluster {
        // Not running in cluster
    }
    // Handle error
}

// Uses:
// - KUBERNETES_SERVICE_HOST environment variable
// - KUBERNETES_SERVICE_PORT environment variable
// - /var/run/secrets/kubernetes.io/serviceaccount/token
// - /var/run/secrets/kubernetes.io/serviceaccount/ca.crt

From Kubeconfig

import "k8s.io/client-go/tools/clientcmd"

// From default location (~/.kube/config)
config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)

// From specific file
config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")

// From master URL and kubeconfig
config, err := clientcmd.BuildConfigFromFlags("https://kubernetes.example.com", kubeconfig)

// From bytes
config, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfigContent))

Manual Configuration

config := &rest.Config{
    Host: "https://kubernetes.example.com:6443",
    BearerToken: "your-token-here",
    TLSClientConfig: rest.TLSClientConfig{
        CAFile: "/path/to/ca.crt",
    },
    QPS:   50.0,
    Burst: 100,
}

Configuration Options

Rate Limiting

config.QPS = 50.0    // Max 50 queries per second
config.Burst = 100   // Allow bursts up to 100

// Disable rate limiting
config.QPS = -1

// Custom rate limiter
config.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(qps, burst)

Timeouts

config.Timeout = 30 * time.Second  // Overall request timeout

// Create HTTP client with custom timeout
httpClient, err := rest.HTTPClientFor(config)
httpClient.Timeout = 60 * time.Second

Impersonation

config.Impersonate = rest.ImpersonationConfig{
    UserName: "system:serviceaccount:default:myapp",
    Groups:   []string{"system:authenticated"},
    Extra: map[string][]string{
        "scopes": []string{"read", "write"},
    },
}

User Agent

config.UserAgent = "my-application/v1.0.0"

// Add to existing user agent
config = rest.AddUserAgent(config, "my-feature/v1.0")

TLS Configuration

config.TLSClientConfig = rest.TLSClientConfig{
    // Use certificate files
    CertFile: "/path/to/client.crt",
    KeyFile:  "/path/to/client.key",
    CAFile:   "/path/to/ca.crt",

    // Or use certificate data directly
    CertData: certBytes,
    KeyData:  keyBytes,
    CAData:   caBytes,

    // Server name for TLS verification
    ServerName: "kubernetes.example.com",

    // Skip TLS verification (not recommended for production)
    Insecure: false,
}

// Load certificate files into data fields
err := rest.LoadTLSFiles(config)

Proxy Configuration

// Use HTTP proxy
config.Proxy = http.ProxyFromEnvironment

// Custom proxy
config.Proxy = func(req *http.Request) (*url.URL, error) {
    return url.Parse("http://proxy.example.com:8080")
}

Creating Clients

RESTClient

// Create generic REST client
restClient, err := rest.RESTClientFor(config)

// With custom HTTP client
httpClient, err := rest.HTTPClientFor(config)
restClient, err := rest.RESTClientForConfigAndClient(config, httpClient)

// Unversioned (no content negotiation)
restClient, err := rest.UnversionedRESTClientFor(config)

Request Builder

// Build and execute requests
result := restClient.
    Get().
    Namespace("default").
    Resource("pods").
    Name("my-pod").
    Do(context.TODO())

// POST request
result := restClient.
    Post().
    Namespace("default").
    Resource("pods").
    Body(podObject).
    Do(context.TODO())

// With options
result := restClient.
    Get().
    Namespace("default").
    Resource("pods").
    VersionedParams(&metav1.ListOptions{
        LabelSelector: "app=myapp",
    }, scheme.ParameterCodec).
    Do(context.TODO())

Helper Functions

// Copy configuration
newConfig := rest.CopyConfig(config)

// Anonymous configuration (remove auth)
anonConfig := rest.AnonymousClientConfig(config)

// Set Kubernetes defaults
err := rest.SetKubernetesDefaults(config)

// Check if TLS is configured
isTLS := rest.IsConfigTransportTLS(*config)

// Create HTTP client
httpClient, err := rest.HTTPClientFor(config)

// Create transport
transport, err := rest.TransportFor(config)

// Create TLS config
tlsConfig, err := rest.TLSConfigFor(config)

Authentication Methods

Bearer Token

config.BearerToken = "eyJhbGciOiJSUzI1NiIs..."

// Or from file
config.BearerTokenFile = "/path/to/token"

Client Certificates

config.TLSClientConfig.CertFile = "/path/to/client.crt"
config.TLSClientConfig.KeyFile = "/path/to/client.key"

Basic Auth

config.Username = "admin"
config.Password = "password"

Exec Provider (for OIDC, etc.)

config.ExecProvider = &clientcmdapi.ExecConfig{
    Command: "kubectl",
    Args:    []string{"oidc-login", "get-token"},
    APIVersion: "client.authentication.k8s.io/v1beta1",
    Env: []clientcmdapi.ExecEnvVar{
        {Name: "KUBERNETES_EXEC_INFO", Value: "..."},
    },
}

Request Interface

type Interface interface {
    GetRateLimiter() flowcontrol.RateLimiter
    Verb(verb string) *Request
    Post() *Request
    Put() *Request
    Patch(pt types.PatchType) *Request
    Get() *Request
    Delete() *Request
    APIVersion() schema.GroupVersion
}

Advanced Configuration

Custom Transport

// Add custom round tripper
config.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {
    return &customRoundTripper{
        base: rt,
    }
}

// Or set transport directly
config.Transport = &http.Transport{
    TLSClientConfig: tlsConfig,
    MaxIdleConns:    100,
    IdleConnTimeout: 90 * time.Second,
}

Warning Handlers

// Suppress warnings
config.WarningHandler = rest.NoWarnings{}

// Log warnings
config.WarningHandler = rest.NewWarningWriter(os.Stderr, rest.WarningWriterOptions{})

// Custom warning handler
config.WarningHandler = myWarningHandler{}

// With context
config.WarningHandlerWithContext = myWarningHandlerWithContext{}

Complete Example

package main

import (
    "context"
    "fmt"
    "time"

    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/clientcmd"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func main() {
    // Load config from kubeconfig
    config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
    if err != nil {
        panic(err)
    }

    // Configure rate limiting
    config.QPS = 50.0
    config.Burst = 100

    // Set timeout
    config.Timeout = 30 * time.Second

    // Set user agent
    config.UserAgent = "my-app/v1.0"

    // Configure impersonation
    config.Impersonate = rest.ImpersonationConfig{
        UserName: "developer",
        Groups:   []string{"developers"},
    }

    // Create clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }

    // Use clientset
    pods, err := clientset.CoreV1().Pods("default").List(
        context.TODO(),
        metav1.ListOptions{})
    if err != nil {
        panic(err)
    }

    fmt.Printf("Found %d pods\n", len(pods.Items))
}

Configuration Loading Priority

When using clientcmd, configurations are loaded and merged in this order:

  1. Command-line flags (highest priority)
  2. $KUBECONFIG environment variable (can be multiple files separated by :)
  3. ~/.kube/config (default location)
  4. In-cluster configuration (lowest priority)

Best Practices

  1. Use InClusterConfig in pods: Always use in-cluster config for applications running in pods
  2. Configure appropriate QPS/Burst: Set rate limits based on your application's needs
  3. Set timeouts: Always configure reasonable request timeouts
  4. Secure credentials: Never hardcode tokens or passwords; use files or environment variables
  5. Use TLS: Always enable TLS verification in production
  6. User Agent: Set meaningful user agents for debugging
  7. Impersonation: Use impersonation for testing RBAC without multiple identities
  8. Warning Handlers: Configure warning handlers to catch API deprecations
  9. Connection pooling: Reuse clients and configs to benefit from connection pooling
  10. Context cancellation: Always pass contexts to support cancellation

Related Documentation

  • Clientsets - Using REST config with typed clients
  • Dynamic Client - Using REST config with dynamic client
  • Tools - Kubeconfig loading and management

Back to Index

Install with Tessl CLI

npx tessl i tessl/golang-k8s-io--client-go

docs

index.md

tile.json