Home > Backend Development > Golang > How to Create and Retrieve Custom Kubernetes Resources using the Go Client Library?

How to Create and Retrieve Custom Kubernetes Resources using the Go Client Library?

Patricia Arquette
Release: 2024-10-31 22:25:02
Original
787 people have browsed it

How to Create and Retrieve Custom Kubernetes Resources using the Go Client Library?

Creating and Retrieving Custom Kubernetes Resources in Go

In Kubernetes, you can define and manage custom resources, which extend the capabilities of the platform. Creating and getting custom resources can be done programmatically using the Go client library.

Creating a Custom Resource

To create a custom resource such as the KongPlugin, you'll need to use the RESTClient of the Kubernetes clientset. Here's how:

<code class="go">// Create a KongPlugin custom resource.
kongPlugin := &KongPlugin{
    TypeMeta: metav1.TypeMeta{
        APIVersion: "configuration.konghq.com/v1",
        Kind:       "KongPlugin",
    },
    ObjectMeta: metav1.ObjectMeta{
        Name: "add-response-header",
    },
    Config: KongPluginConfig{
        Add: KongPluginConfigAdd{
            Headers: []string{"demo: injected-by-kong"},
        },
    },
    Plugin: "response-transformer",
}

body, err := json.Marshal(kongPlugin)
if err != nil {
    panic(err)
}

data, err := clientset.RESTClient().
    Post().
    AbsPath("/apis/configuration.konghq.com/v1/namespaces/" + namespace + "/kongplugins").
    Body(body).
    DoRaw(context.TODO())</code>
Copy after login

Retrieving a Custom Resource

To retrieve a custom resource, you can use the Get() method of the RESTClient:

<code class="go">// Get the KongPlugin custom resource.
data, err := clientset.RESTClient().
    Get().
    AbsPath("/apis/configuration.konghq.com/v1/namespaces/" + namespace + "/kongplugins/add-response-header").
    DoRaw(context.TODO())</code>
Copy after login

AbsPath() Notes:

  • The AbsPath() method takes the full absolute path to the Kubernetes resource.
  • To find the resource's absolute path, use kubectl get -o=jsonpath='{$.metadata.selfLink}'.
  • Alternatively, you can specify the path manually by including the API group, version, namespace, and resource type.

The above is the detailed content of How to Create and Retrieve Custom Kubernetes Resources using the Go Client Library?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template