Simple integration of client go gin (list related operations)

Background:

It's done Client go connect kubernetes cluster delete related operations , I've seen some stops B Qimiao who can write js best in go circle Videos of go and gin, and some courses of Uncle Shen: https://www.jtthink.com/ . Generally, they are used to doing it first and do it by themselves. If there is a problem, see Uncle Shen's video and solutions!

1. Simple integration of client go gin

Note: there may be some differences in the following operating environments (windows for writing at home, and a rocky linux is installed in the company's office environment). Next, all paths are relative paths under the k8s-demo1 project directory!

1. go get install gin dependency

PS C:\Users\zhangpeng\GolandProjects\k8s-demo1> go get github.com/gin-gonic/gin
go get: added github.com/gin-contrib/sse v0.1.0
go get: added github.com/gin-gonic/gin v1.7.7
go get: added github.com/go-playground/locales v0.13.0
go get: added github.com/go-playground/universal-translator v0.17.0
go get: added github.com/go-playground/validator/v10 v10.4.1
go get: added github.com/leodido/go-urn v1.2.0
go get: added github.com/mattn/go-isatty v0.0.12
go get: added github.com/ugorji/go/codec v1.1.7


Note: the operation in linux environment is omitted... If an error is reported and other dependencies are missing, go get will get the installation by itself according to the prompt!

2. Encapsulate the connection client into a method file

Split the separate files written in the previous test environment. Encapsulate the client into a single file:
lib/K8sClient.go

package lib

import (
	"flag"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"path/filepath"
)

var K8sClient *kubernetes.Clientset

func init() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// create the clientset
	c, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	K8sClient = c
}

3. Create the service directory and create the service file corresponding to the namespace deployment service

Take the namespace deployment service as an example:

src/service/Namespace.go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func ListNamespace(g *gin.Context) {
	ns, err := K8sClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
	if err != nil {
		g.Error(err)
		return
	}
	g.JSON(200, ns)
}

src/service/Deployment.go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func ListDeployment(g *gin.Context) {
	ns := g.Query("ns")

	dps, err := K8sClient.AppsV1().Deployments(ns).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		g.Error(err)
	}
	g.JSON(200, dps)
	return
}

src/service/Service.go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func ListService(g *gin.Context) {
	ns := g.Query("ns")
	svc, err := K8sClient.CoreV1().Services(ns).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		g.Error(err)
		return
	}
	g.JSON(200, svc)
}

Note: normal should be lib K8sclient reference. import is set to “k8s-demo1/src/lib”!

4. Edit main Go set route

main.go

package main

import (
	"github.com/gin-gonic/gin"
	"k8s-demo1/src/service"
)

func main() {
	r := gin.Default()
	r.GET("/", func(context *gin.Context) {
		context.JSON(200, "hello")
	})
	r.GET("/namespaces", service.ListNamespace)
	r.GET("/deployments", service.ListDeployment)
	r.GET("/service", service.ListService)
	r.Run()
}

5. Run main Go, whether the browser access returns normally

You can use the command line console go run main Go or goland can directly run main go

Note: this cluster is not the previous ack cluster, but a test cluster in the local intranet! Therefore, the output of namespace and other related information does not correspond to the previous part

1. namespace:

http://127.0.0.1:8080/namespaces

2. deployment

http://127.0.0.1:8080/deployments

http://127.0.0.1:8080/deployments?ns=default Specify namespace

3. service

http://127.0.0.1:8080/service

http://127.0.0.1:8080/service?ns=default Specify namespace

Basically achieved personal goals. But the output content is too much, many things do not need, want to further optimize the output of their first information!

2. Further - customize the content required for output

1. About namespace

namespace I just want to output the space name! Create a struct and make a slice:
src/service/Namespace.go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Namespace struct {
	Name string
}

func ListNamespace(g *gin.Context) {
	ns, err := K8sClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
	if err != nil {
		g.Error(err)
		return
	}
	ret := make([]*Namespace, 0)
	for _, item := range ns.Items {
		ret = append(ret, &Namespace{
			Name: item.Name,
		})

	}
	g.JSON(200, ret)
	return
}


Browser access http://127.0.0.1:8080/namespaces , as follows:

2. About deployment

Refer to namespace to set Src / service / deployment go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Deployment struct {
	Name string
}

func ListDeployment(g *gin.Context) {
	ns := g.Query("ns")

	dps, err := K8sClient.AppsV1().Deployments(ns).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		g.Error(err)
	}
	ret := make([]*Deployment, 0)
	for _, item := range dps.Items {
		ret = append(ret, &Deployment{
			Name: item.Name,
		})

	}
	g.JSON(200, ret)
	return
}

Run main Go visit http://127.0.0.1:8080/deployments http://127.0.0.1:8080/deployments?ns=default

3. About service

src/service/Service.go as follows

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Service struct {
	Name string
}

func ListService(g *gin.Context) {
	ns := g.Query("ns")
	svc, err := K8sClient.CoreV1().Services(ns).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		g.Error(err)
		return
	}
	ret := make([]*Service, 0)
	for _, item := range svc.Items {
		ret = append(ret, &Service{
			Name: item.Name,
		})

	}
	g.JSON(200, ret)
	return
}

Run main Go visit http://127.0.0.1:8080/service http://127.0.0.1:8080/service?ns=default

reflect:

1. Use of slice and pointer
2. Customize the output of more relevant configurations? For example, the number of images and replicas in deployments. label in namespace? Creation time?
3.gin. How can I understand context

Tags: Go Kubernetes Container DevOps Cloud Native client-go

Posted by M4F on Thu, 05 May 2022 14:02:09 +0300