天天看點

Go名庫欣賞-uitable:終端資料表格展示工具

一、前言

最近發現go用作一個運維工具是真的很好用,我覺得比python好用多了,python的依賴太麻煩了,而go作為運維工具可以直接打包成二進制包,可移植性極好,而且go天生對linux親和性極強。像k8s的一個強大的運維指令-

kubectl

,列印的資料都是以表格的形式展示,表達能力很強,像實作這種終端表格展示有一個好用的工具-

uitable

二、内容

這是我用

kubectl get pods

列印的一個終端界面:

NAME       READY   STATUS    RESTARTS   AGE
nginx1-0   1/1     Running   0          11d
nginx2-0   1/1     Running   0          11d
           

那麼用該該庫怎麼實作呢?

type pod struct {
	NAME, READY, STATUS, AGE string
	RESTARTS                 int
}

var pods = []pod{
	{"nginx1-0 ", "1/1", "Running", "11d", 0},
	{"nginx2-0", "1/1", "Running", "11d", 0},
}

func main() {
	table := uitable.New()
	table.MaxColWidth = 50

	table.AddRow("NAME", "READY", "STATUS", "RESTARTS", "AGE")
	for _, pod := range pods {
		table.AddRow(pod.NAME, pod.READY, pod.STATUS, pod.AGE, pod.RESTARTS)
	}
	fmt.Println(table)
}
           

執行代碼的結果如下:

NAME            READY   STATUS  RESTARTS        AGE
nginx1-0        1/1     Running 11d             0  
nginx2-0        1/1     Running 11d             0  
           

可以發現基本和k8s的輸出一模一樣。到這裡或許有人會說:就這?

下面給大家展示另外一個功能:改變字型顔色輸出。如果你的工具用上這麼一個功能,還不能顯示出你的逼格嗎?當然這裡會使用到另外一個庫,配合使用才行

github.com/fatih/color

修改如下代碼:

type pod struct {
	NAME, READY, STATUS, AGE string
	RESTARTS                 int
}

var pods = []pod{
	{"nginx1-0 ", "1/1", "Running", "11d", 0},
	{"nginx2-0", "1/1", "Running", "11d", 0},
}

func main() {
	table := uitable.New()
	table.MaxColWidth = 100
	table.RightAlign(10)

	table.AddRow("NAME", "READY", "STATUS", "RESTARTS", "AGE")
	for _, pod := range pods {
		table.AddRow(color.RedString(pod.NAME), color.WhiteString(pod.READY), color.BlueString(pod.STATUS), color.GreenString(pod.AGE), color.YellowString("%d", pod.RESTARTS))
	}
	fmt.Println(table)
}
           

列印的效果如下:

Go名庫欣賞-uitable:終端資料表格展示工具

三、總結

經測試,該包可以在

mac

linux

windows

上都能使用,包括上面示範的不同顔色的字型的包也能跨平台使用。

  • 我的微信公衆号:
    Go名庫欣賞-uitable:終端資料表格展示工具

繼續閱讀