Search code examples
kubernetesclient-gokubernetes-custom-resources

How to query a CR for a given namespace using client-go RESTClient() function


This golang code works well:

    topics := &kafka.KafkaTopicList{}
    d, err := clientSet.RESTClient().Get().AbsPath("/apis/kafka.strimzi.io/v1beta2/kafkatopics").DoRaw(context.TODO())
    if err != nil {
        panic(err.Error())
    }

However I'd like to get the kafkatopics custom resources only for a given namespace, is there a way to do this using client-go api? For information, using clientSet.RESTClient().Get().Namespace("<my-namespace>") returns the following error message: "the server could not find the requested resource"


Solution

  • Try:

    group := "kafka.strimzi.io"
    version := "v1beta2"
    plural := "kafkatopics"
    
    namespace := "..."
    
    d, err := clientSet.RESTClient().Get().AbsPath(
        fmt.Sprintf("/apis/%s/%s/namespaces/%s/%s",
            group,
            version,
            namespace,
            plural,
        ).DoRaw(context.TODO())
    if err != nil {
        panic(err.Error())
    }
    

    I think using CRDs, client-go's Namespace method incorrectly appends namespace/{namespace} into the request URL with CRDs.

    You want:

    /apis/{group}/{version}/namespaces/{namespace}/{plural}
    

    Using Namespace, you get:

    /apis/{group}/{version}/{plural}/namespaces/{namespace}
    

    You can prove this to yourself with:

    log.Println(restClient.Get().Namespace(namespace).AbsPath(
        fmt.Sprintf("/apis/%s/%s/%s",
            group,
            version,
            plural,
        ),
    ).URL().String())