search
HomeBackend DevelopmentGolangHow to get 'friendly' responses from Kubernetes APIServer using ReST interface

如何使用 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. If there is any infringement, please contact admin@php.cn delete
Testing Code that Relies on init Functions in GoTesting Code that Relies on init Functions in GoMay 03, 2025 am 12:20 AM

WhentestingGocodewithinitfunctions,useexplicitsetupfunctionsorseparatetestfilestoavoiddependencyoninitfunctionsideeffects.1)Useexplicitsetupfunctionstocontrolglobalvariableinitialization.2)Createseparatetestfilestobypassinitfunctionsandsetupthetesten

Comparing Go's Error Handling Approach to Other LanguagesComparing Go's Error Handling Approach to Other LanguagesMay 03, 2025 am 12:20 AM

Go'serrorhandlingreturnserrorsasvalues,unlikeJavaandPythonwhichuseexceptions.1)Go'smethodensuresexpliciterrorhandling,promotingrobustcodebutincreasingverbosity.2)JavaandPython'sexceptionsallowforcleanercodebutcanleadtooverlookederrorsifnotmanagedcare

Best Practices for Designing Effective Interfaces in GoBest Practices for Designing Effective Interfaces in GoMay 03, 2025 am 12:18 AM

AneffectiveinterfaceinGoisminimal,clear,andpromotesloosecoupling.1)Minimizetheinterfaceforflexibilityandeaseofimplementation.2)Useinterfacesforabstractiontoswapimplementationswithoutchangingcallingcode.3)Designfortestabilitybyusinginterfacestomockdep

Centralized Error Handling Strategies in GoCentralized Error Handling Strategies in GoMay 03, 2025 am 12:17 AM

Centralized error handling can improve the readability and maintainability of code in Go language. Its implementation methods and advantages include: 1. Separate error handling logic from business logic and simplify code. 2. Ensure the consistency of error handling by centrally handling. 3. Use defer and recover to capture and process panics to enhance program robustness.

Alternatives to init Functions for Package Initialization in GoAlternatives to init Functions for Package Initialization in GoMay 03, 2025 am 12:17 AM

InGo,alternativestoinitfunctionsincludecustominitializationfunctionsandsingletons.1)Custominitializationfunctionsallowexplicitcontroloverwheninitializationoccurs,usefulfordelayedorconditionalsetups.2)Singletonsensureone-timeinitializationinconcurrent

Type Assertions and Type Switches with Go InterfacesType Assertions and Type Switches with Go InterfacesMay 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Using errors.Is and errors.As for Error Inspection in GoUsing errors.Is and errors.As for Error Inspection in GoMay 02, 2025 am 12:11 AM

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

Performance Tuning in Go: Optimizing Your ApplicationsPerformance Tuning in Go: Optimizing Your ApplicationsMay 02, 2025 am 12:06 AM

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment