Home  >  Article  >  Backend Development  >  How to get "friendly" responses from Kubernetes APIServer using ReST interface

How to get "friendly" responses from Kubernetes APIServer using ReST interface

WBOY
WBOYforward
2024-02-09 08:10:181182browse

如何使用 ReST 接口从 Kubernetes APIServer 获取“友善”响应

php editor Apple will introduce to you how to use the ReST interface to obtain a "friendly" response from the Kubernetes APIServer. Kubernetes is a popular container orchestration platform that provides APIs to manage and monitor various resources in the cluster. By using the ReST interface, we can easily interact with the Kubernetes APIServer and obtain the information we need. In this article, we will explore in detail how to authenticate, send requests and handle responses using the ReST interface, as well as how to handle possible error conditions. Whether you are new to Kubernetes or an experienced Kubernetes user, this article will provide you with useful guidance and practical advice.

Question content

I am using golang client-go library to communicate with kubernetes api server at rest get, post level. The response received is not a well-formed json structure, nor is it a "kind" of api object.

The program fragment is:

kubeconfig := filepath.join(
         os.getenv("home"), ".kube", "config",
    )
    config, err := clientcmd.buildconfigfromflags("", kubeconfig)
    if err != nil {
        log.fatal(err)
    }
    config.negotiatedserializer = scheme.codecs.withoutconversion()


    groupversion, _ := schema.parsegroupversion("api/v1")
    config.groupversion = &groupversion
    config.contenttype = "application/json"

    config.acceptcontenttypes = "application/json"
    
    examplerestclient, err := rest.restclientfor(config)
    if err != nil {
        panic(err)
    }
    
    var statuscode int
    var contenttype string

    response, err := examplerestclient.
        get().
        resource("nodes").
        do(context.background()).
        statuscode(&statuscode).
        contenttype(&contenttype).
        get()
    
    if err != nil {
        panic(err)
    }

    fmt.printf("content-type is %s\n", contenttype)
    fmt.printf("status code is %d\n", statuscode)

    fmt.printf("received response %v\n", response)

The response starts with:

status code is 200
received response &nodelist{listmeta:{ 17299  <nil>},items:[]node{node{objectmeta:{dev-cluster-control-plane    7fe038c9-8be6-41a9-9f3f-5900abb0e34b 16922 0 2023-02-19 16:32:44 +0530 ist <nil> <nil> map[beta.kubernetes.io/arch:amd64 beta.kubernetes.io/os:linux kubernetes.io/arch:amd64 kubernetes.io/hostname:dev-cluster-control-plane kubernetes.io/os:linux node-role.kubernetes.io/control-plane: node.kubernetes.io/exclude-from-external-load-balancers:] map[kubeadm.alpha.kubernetes.io/cri-socket:unix:///run/containerd/containerd.sock node.alpha.kubernetes.io/ttl:0 volumes.kubernetes.io/controller-managed-attach-detach:true] [] [] ...

I expect output similar to what the following command returns:

$ kubectl get --raw /api/v1/nodes
{"kind":"NodeList","apiVersion":"v1","metadata":{"resourceVersion":"17481"},"items":[{"metadata":{"name":"dev-cluster-control-plane","uid":"7fe038c9-8be6-41a9-9f3f-5900abb0e34b","resourceVersion":"17351","creationTimestamp":"2023-02-19T11:02:44Z","labels":{"beta.kubernetes.io/arch":"amd64","beta.kubernetes.io/os":"linux","kubernetes.io/arch":"amd64","kubernetes.io/hostname":"dev-cluster-control-plane","kubernetes.io/os":"linux","node-role.kubernetes.io/control-plane":"","node.kubernetes.io/exclude-from-external-load-balancers":""},"annotations":{"kubeadm.alpha.kubernetes.io/cri-socket":"unix:///run/containerd/containerd.sock","node.alpha.kubernetes.io/ttl":"0" ...

Solution

The response received is not a well-formed json structure

I think you are confused about how the client-go module works.

The response from the rest api is definitely a well-formed json response, but this will be unmarshaled into a go data structure (such as this).

If you want to access the returned nodes, you can interact with the results using standard go syntax:

response, err := examplerestclient.
  get().
  resource("nodes").
  do(context.background()).
  statuscode(&statuscode).
  contenttype(&contenttype).
  get()

if err != nil {
  panic(err)
}

nodes := response.(*v1.nodelist)
for _, node := range nodes.items {
  fmt.printf("name: %s\n", node.objectmeta.getname())
  fmt.printf("addresses:\n")
  for _, addr := range node.status.addresses {
    fmt.printf("  %s: %s\n", addr.type, addr.address)
  }
}

I expect output similar to what the following command returns:

Why? client-go Bindings return data useful to your go code. If you want to generate json output, you need to explicitly marshal the resource to json format:
response, err := exampleRestClient.
  Get().
  Resource("nodes").
  Do(context.Background()).
  StatusCode(&statusCode).
  ContentType(&contentType).
  Get()

if err != nil {
  panic(err)
}

out, err := json.Marshal(response)
fmt.Print(string(out))

The above is the detailed content of How to get "friendly" responses from Kubernetes APIServer using ReST interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete