Reading a Custom Resource with the Dynamic Client in Golang

Open-Source AI Gateway & Developer Portal
In the realm of software development, particularly in the context of cloud-native applications and microservices architectures, working with APIs is paramount. One of the most effective ways to interface with Kubernetes APIs is using the dynamic client in Golang. This approach allows developers to interact with custom resources flexibly and efficiently while also maintaining the scalability and reusability typical of cloud-native applications. In this article, we'll delve deeply into how to read a custom resource using the dynamic client in Golang while also discussing relevant concepts such as API Gateway and OpenAPI.
Why Read Custom Resources?
Custom resources are an integral part of Kubernetes that enables users to extend the Kubernetes API with their custom objects. This can be particularly useful when building applications that require special configurations or resources beyond what the standard Kubernetes resources (Pods, Deployments, Services, etc.) provide.
By reading custom resources, developers can: - Automate application deployment through resource specification. - Integrate external services efficiently. - Enhance service discovery and orchestration. - Implement complex workflows based on Kubernetes’ extensibility.
In this regard, understanding API concepts including the definitions provided through OpenAPI specifications becomes crucial. OpenAPI allows developers to define their RESTful APIs in a machine-readable format, which can enhance documentation, client generation, and validation.
Key Concepts
Dynamic Client in Golang
The dynamic client in Golang allows developers to interact with Kubernetes APIs without the need for a concrete type definition. This is particularly advantageous when working with custom resources as it provides flexibility that static types might not offer. Using the dynamic client, we can read, write, and manipulate Kubernetes resources swiftly.
API Gateway
An API gateway serves as a single entry point for various API services within an application. It can handle incoming traffic, direct requests to various microservices, and enforce security controls. This architecture simplifies communication, particularly in applications composed of multiple services. The API gateway becomes a critical component, especially when it comes to logging, monitoring, and managing API traffic.
OpenAPI
OpenAPI is a widely used specification for documenting REST APIs effectively. It allows developers to define how APIs should behave, including the endpoints available, the operations permitted, the request and response formats, and other relevant metadata. This can significantly enhance front-end and back-end collaboration and streamline the development process.
Setup: Creating Your Environment
Before diving into the coding aspect, ensure you have the following prerequisites:
- Go installed on your machine. Preferably version 1.15+.
- A functioning Kubernetes cluster where you can deploy your custom resources.
- The
kubectl
command-line tool configured to interact with your cluster.
Installing Necessary Libraries
You'll need to install the following Go libraries:
go get k8s.io/client-go@v0.21.0
go get k8s.io/apimachinery@v0.21.0
You can also utilize dependencies management tools like go modules
to manage your project.
APIPark is a high-performance AI gateway that allows you to securely access the most comprehensive LLM APIs globally on the APIPark platform, including OpenAI, Anthropic, Mistral, Llama2, Google Gemini, and more.Try APIPark now! 👇👇👇
Creating a Custom Resource Definition (CRD)
To read a custom resource, you first need to define it within your Kubernetes cluster. Here's an example of a simple CRD definition that describes a Book
resource.
CRD YAML Specification
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: books.example.com
spec:
group: example.com
names:
kind: Book
listKind: BookList
plural: books
singular: book
scope: Namespaced
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
title:
type: string
author:
type: string
publishedAt:
type: string
This CRD allows you to create Book
resources within any namespace in your Kubernetes cluster.
Deploying the CRD Using kubectl
Save the above YAML in a file named book-crd.yaml
and deploy it by running:
kubectl apply -f book-crd.yaml
Now your Kubernetes cluster is equipped with a custom resource, allowing you to manage Book
resources.
Code for Reading Custom Resource Using Dynamic Client
Now that we have our environment set up and the CRD deployed, let’s write a Go program that reads Book
resources from the Kubernetes cluster using the dynamic client.
Create the Main Go File
Create a new Go file named main.go
and implement the following code:
package main
import (
"context"
"fmt"
"os"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
)
func main() {
// Build the Kubernetes client configuration
kubeconfig := os.Getenv("KUBECONFIG")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
// Create a dynamic client
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// Define the GVR (Group-Version-Resource) for the Book custom resource
gvr := schema.GroupVersionResource{
Group: "example.com",
Version: "v1",
Resource: "books",
}
// Read the Book resources from a specific namespace
namespace := "default"
books, err := dynamicClient.Resource(gvr).Namespace(namespace).List(context.TODO(), v1.ListOptions{})
if err != nil {
panic(err.Error())
}
// Output the list of books
for _, book := range books.Items {
fmt.Printf("Book Name: %s\n", book.GetName())
fmt.Printf("Book Details: %v\n", book)
}
}
Explanation of the Code
- Configuration: The code begins by building the Kubernetes client configuration. It uses the
KUBECONFIG
environment variable to find the configuration file. - Dynamic Client Creation: It creates a dynamic client that enables interactions with Kubernetes’ various resources without predefined types.
- GroupVersionResource (GVR): A
GVR
is defined for theBook
custom resource, specifying its group, version, and resource type. - Listing Books: The code retrieves
Book
resources from the specified namespace (default
in this case) and prints their names and details.
Running the Code
You can run your program with the following command:
go run main.go
Ensure that you have at least one Book
resource created in your specified namespace; otherwise, the output will show nothing.
Conclusion
Reading custom resources with the dynamic client in Golang enables developers to manipulate Kubernetes’ extensible functionality to suit their application needs. By leveraging Kubernetes’ dynamic capabilities, you can enhance your APIs’ effectiveness, integrate with numerous microservices, and simplify your cloud-native application's architecture.
Moreover, integrating an API gateway such as APIPark can bring considerable value to your application management and API utilization. APIPark serves not only to streamline the microservices communication but also enhances security and performance, making it an essential tool for modern development practices.
In this article, we've covered the essential steps for setting up, reading custom resources using the dynamic client, and discussed how these practices fit into broader API architectures.
FAQ
- What is a custom resource in Kubernetes? A custom resource allows you to extend the Kubernetes API with your own defined resources, thereby enabling specialized application configurations.
- How do I create a custom resource in Kubernetes? You create a custom resource by defining a Custom Resource Definition (CRD) and implementing the desired specifications, then deploy it to your Kubernetes cluster.
- What is the dynamic client in Golang? The dynamic client is a versatile client that enables Kubernetes API interactions without needing explicit type definitions. It's especially useful for reading and manipulating custom resources.
- What are the advantages of using an API Gateway? An API gateway simplifies API management and provides a unified entry point for microservices, traffic management, usage metrics, and enhanced security.
- How can APIPark assist in API management? APIPark is an all-in-one platform for managing APIs, providing functionalities for lifecycle management, performance monitoring, and integrating with various AI models, making it a comprehensive solution for developers and enterprises.
🚀You can securely and efficiently call the OpenAI API on APIPark in just two steps:
Step 1: Deploy the APIPark AI gateway in 5 minutes.
APIPark is developed based on Golang, offering strong product performance and low development and maintenance costs. You can deploy APIPark with a single command line.
curl -sSO https://download.apipark.com/install/quick-start.sh; bash quick-start.sh

In my experience, you can see the successful deployment interface within 5 to 10 minutes. Then, you can log in to APIPark using your account.

Step 2: Call the OpenAI API.
