如何在Go中为控制台/终端输出添加颜色

许多关于 bash 的文章都建议使用看起来像\e[39m漂亮颜色的东西,虽然这些在 bash 中工作得很好,但对于 Go 来说却是另一回事——字符串只是按原样呈现。然而,有一些库可以让您为输出着色,但是代码太臃肿了,您甚至无法找到要解决的问题的答案。

毕竟,并不是每个人都想仅仅为了颜色而导入一个库。

不使用第三方库

因此,我为您带来了为您的控制台着色的最简单方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package color

import "runtime"

var Reset = "\033[0m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var Purple = "\033[35m"
var Cyan = "\033[36m"
var Gray = "\033[37m"
var White = "\033[97m"

func init() {
if runtime.GOOS == "windows" {
Reset = ""
Red = ""
Green = ""
Yellow = ""
Blue = ""
Purple = ""
Cyan = ""
Gray = ""
White = ""
}
}

如您所知,Windows 不支持开箱即用的命令行中的颜色,因此,检查运行时init并在运行时将所有颜色设置为空字符串windows将解决此问题,而无需到处打印丑陋的字符你的控制台。

显然,有很多方法可以让它在好的 ol’ 命令提示符下工作,但由于 Windows 10 的 WSL(Linux 的 Windows 子系统)是一个东西,如果你想要漂亮的颜色,你可以使用它而无需挣扎。

用法

您所要做的就是在要着色的文本之前color.YOUR_COLOR 添加并添加color.Reset在同一文本的末尾。如果您不使用 重置颜色Color.Reset,您的控制台/终端将在会话的其余部分保持相同的颜色,所以不要忘记它。

1
2
3
4
5
6
7
8
9
10
func main() {
println(color.White + "This is White" + color.Reset)
println(color.Red + "This is Red" + color.Reset)
println(color.Green + "This is Green" + color.Reset)
println(color.Yellow + "This is Yellow" + color.Reset)
println(color.Blue + "This is Blue" + color.Reset)
println(color.Purple + "This is Purple" + color.Reset)
println(color.Cyan + "This is Cyan" + color.Reset)
println(color.Gray + "This is Gray" + color.Reset)
}

去颜色

使用go-color库

如果你更愿意使用一个库,你可以看看TwinProduction/go-color,这是一个非常轻量级的库,我厌倦了在几个项目中重新实现相同的东西:

1
2
3
4
5
6
7
8
9
package main

import "github.com/TwinProduction/go-color"

func main() {
println(color.Ize(color.Red, "This is red"))
// Or if you prefer the longer version
println(color.Colorize(color.Red, "This is also red"))
}

本文翻译自 How to add colors to your console/terminal output in Go

如何在Go中为控制台/终端输出添加颜色

https://ganzhixiong.com/p/9f76eb4e/

Author

干志雄

Posted on

2021-07-07

Updated on

2021-07-07

Licensed under

Comments