This is an explanation of the video content.
 用技术延续对ACG的热爱
145
 | 
[Go开源库]Color: 一个让终端内容彩色化的工具

在命令行的文本输出中,你经常见到的是不是都是黑色背景,白色文字。给大家推荐一款能让输出的文本带上颜色的工具:color

color工具能够使终端上的输出按不同的颜色输出。

该工具不仅可以让内容按不同颜色输出,还可以给内容加上粗体、斜体、下划线的样式。同时还可以给美容加上背景颜色。下面我们看下具体的使用。

首先,通过go get命令安装该color包:

go get github.com/fatih/color

接下来我们就可以在程序中将文本按不同的颜色输出了:

// Print with default helper functions
color.Cyan("Prints text in cyan.")

// A newline will be appended automatically
color.Blue("Prints %s in blue.", "text")

// These are using the default foreground colors
color.Red("We have red")
color.Magenta("And many others ..")

下面是让文本以红色、粗体、白色背景 输出:


// Mix up foreground and background colors, create new mixes!
red := color.New(color.FgRed)

boldRed := red.Add(color.Bold)
boldRed.Println("This will print text in bold red.")

whiteBackground := red.Add(color.BgWhite)
whiteBackground.Println("Red text with white background.")

实现原理分析:其实现原理实际上是应用了ANSI换码符。所谓换码符就是一套编码规则,用于控制终端上的光标位置、颜色和其他选项。以下就是利用换码符实现的基本代码:

const escape = "\x1b" //ascii码表中对应escape的编码
f := fmt.Sprintf("%s[%sm", escape, "34")

fmt.Fprint(os.Stdout, f)
fmt.Fprintln(os.Stdout, "Hello World in blue")

在第1、2行中,通过传递一个escape常量表示来告诉设备后面的字符是命令字符,根据标准的ANSI换码符列表定义的含义,设备按该命令执行具体操作。ANSI换码符列表可参考:https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797

更多项目详情请查看如下链接。

开源项目地址:https://github.com/fatih/color

开源项目作者:Fatih Arslan



145 服务端 ↦ Go开发技巧 __ 111 字
 Go开发技巧 #3