Go语言库系列之aurora
source link: https://studygolang.com/articles/27703
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
背景介绍
今天跟大家推荐一款可以给终端输出上色的工具--aurora。
极速上手
准备工作
初始化项目
go mod init aurora
演示项目结构
. ├── go.mod ├── go.sum └── main.go
安装aurora包
go get -u github.com/logrusorgru/aurora
代码演示
首先引入aurora库
import . "github.com/logrusorgru/aurora"
输出一个品红颜色的内容,Magenta是以颜色命名的方法
fmt.Println("Hello,", Magenta("Aurora"))
再输出一个加粗的青色的名称
fmt.Println(Bold(Cyan("Cya!")))
完整代码如下
package main import ( "fmt" . "github.com/logrusorgru/aurora" ) func main() { fmt.Println("Hello,", Magenta("Aurora")) fmt.Println(Bold(Cyan("Cya!"))) }
运行后输出内容如下
更多玩法
支持格式化输出函数
除了换行输出函数外,aurora还支持格式化输出函数
msg := fmt.Sprintf("My name is %s", Green("pingyeaa")) fmt.Println(msg)
链式调用
我们可以嵌套调用,来个绿底加粗红字
fmt.Println(BgGreen(Bold(Red("pingyeaa"))))
还可以进行链式调用,同样可以达到相同效果,这种方式的可读性更高一些
fmt.Println(Red("pingyeaa").Bold().BgGreen())
更简便的写法
除了链式调用外,还有一种更简便的写法,就是通过位或运算符来实现
fmt.Println(Colorize("Greeting", GreenFg|RedBg|BoldFm))
官方定义了10种常量,感兴趣的同学可以自行研究源码
const ( BlackBg Color = (iota << shiftBg) | flagBg // 40, 100 RedBg // 41, 101 GreenBg // 42, 102 YellowBg // 43, 103 BlueBg // 44, 104 MagentaBg // 45, 105 CyanBg // 46, 106 WhiteBg // 47, 107 BrightBg Color = ((1 << 3) << shiftBg) | flagBg // -> 100 BrownBg = YellowBg maskBg = (0xff << shiftBg) | flagBg )
同样也可以搭配链式调用使用
fmt.Println(Red("x").Colorize(GreenFg))
支持灰阶
所谓灰阶,是将最亮与最暗之间的亮度变化,区分为若干份
方法中的数字代表灰色深度的数值,支持背景和文字上色
fmt.Println(" ", Gray(1-1, " 00-23 ").BgGray(24-1), Gray(4-1, " 03-19 ").BgGray(20-1), Gray(8-1, " 07-15 ").BgGray(16-1), Gray(12-1, " 11-11 ").BgGray(12-1), Gray(16-1, " 15-07 ").BgGray(8-1), Gray(20-1, " 19-03 ").BgGray(4-1), Gray(24-1, " 23-00 ").BgGray(1-1), )
支持闪烁
fmt.Println(Blink("Blink"))
限制
格式化输出函数中的 %T
与 %p
是没办法上色的
r := Red("red") var i int fmt.Printf("%T %p\n", r, Green(&i))
aurora.value %!p(aurora.value={0xc42000a310 768 0})
但是可以通过在外层嵌套颜色来解决
fmt.Println(Red(fmt.Sprintf("%T %p\n", r, Green(&i))))
Go语言库代码示例,欢迎star
https://github.com/pingyeaa/g...
感谢大家的观看,如果觉得文章对你有所帮助,欢迎关注公众号「平也」,聚焦Go语言与技术原理。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK