要建立和擷取自訂 Kubernetes 資源,您需要使用 RESTClient 並指定自訂資源的 API 路徑和版本。
要建立自訂資源,例如KongPlugin,可以使用以下程式碼:
<code class="go">import "k8s.io/client-go/rest" func CreateCustomResource() error { // Construct the full path to the custom resource absPath := "/apis/configuration.konghq.com/v1/namespaces/default/kongplugins" // Marshal the custom resource data into a byte array body, err := json.Marshal(customResource) if err != nil { return err } // Create a RESTClient using in-cluster configuration confs, err := rest.InClusterConfig() if err != nil { return err } client, err := rest.RESTClientFor(confs) if err != nil { return err } // Make a POST request to create the custom resource _, err = client.Post().AbsPath(absPath).Body(body).DoRaw() if err != nil { return err } return nil }</code>
要擷取自訂資源,您可以使用以下程式碼:
<code class="go">import "k8s.io/client-go/rest" func GetCustomResource() (*CustomResource, error) { // Construct the full path to the custom resource absPath := "/apis/configuration.konghq.com/v1/namespaces/default/kongplugins/kongplugin-sample" // Create a RESTClient using in-cluster configuration confs, err := rest.InClusterConfig() if err != nil { return nil, err } client, err := rest.RESTClientFor(confs) if err != nil { return nil, err } // Make a GET request to retrieve the custom resource data, err := client.Get().AbsPath(absPath).DoRaw() if err != nil { return nil, err } // Unmarshal the JSON response into the custom resource object customResource := &CustomResource{} if err := json.Unmarshal(data, customResource); err != nil { return nil, err } return customResource, nil }</code>
以上是如何使用 RESTClient 建立和檢索自訂 Kubernetes 資源?的詳細內容。更多資訊請關注PHP中文網其他相關文章!