最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

go - Check if resource, version apiGroup is known in Scheme - Stack Overflow

programmeradmin2浏览0评论

Input: resource, version apiGroup is known in Scheme

For example:

    resource := "pods"
    version := "v1"
    apiGroup := ""

How can I check if that is known in the scheme?

Background: I want to validate the resource string in CI.

I do not have a connection to an api-server.

I found that solution, but it feels very ugly because it does lower-case the string and adds an s.

How to check if the resource is registered without "magic" string manipulation?

package main

import (
    "fmt"
    "log"
    "strings"

    "k8s.io/apimachinery/pkg/runtime/schema"
    "k8s.io/client-go/kubernetes/scheme"
)

func main() {
    // Define the resource, version, and API group
    resource := "pods"
    version := "v1"
    apiGroup := ""

    // Check if the GroupVersion is registered in the scheme
    gvkList := scheme.Scheme.AllKnownTypes()
    found := false

    for gvk := range gvkList {
        if gvk.Group == apiGroup && gvk.Version == version {
            plural := strings.ToLower(gvk.Kind) + "s" // Simple pluralization, adjust as needed
            if plural == resource {
                fmt.Printf("Resource %s with version %s in group %s is registered in the scheme\n", resource, version, apiGroup)
                found = true
                break
            }
        }
    }

    if !found {
        log.Fatalf("Resource %s with version %s in group %s is not registered in the scheme", resource, version, apiGroup)
    }
}

发布评论

评论列表(0)

  1. 暂无评论