Go語言庫系列之aurora
阿新 • • 發佈:2020-04-05
## 背景介紹
今天跟大家推薦一款可以給終端輸出上色的工具--aurora。
![file](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145328792-7426586.jpg)
## 極速上手
### 準備工作
初始化專案
```shell
go mod init aurora
```
演示專案結構
```shell
.
├── go.mod
├── go.sum
└── main.go
```
安裝aurora包
```shell
go get -u github.com/logrusorgru/aurora
```
### 程式碼演示
首先引入aurora庫
```go
import . "github.com/logrusorgru/aurora"
```
輸出一個品紅顏色的內容,Magenta是以顏色命名的方法
```go
fmt.Println("Hello,", Magenta("Aurora"))
```
再輸出一個加粗的青色的名稱
```go
fmt.Println(Bold(Cyan("Cya!")))
```
完整程式碼如下
```go
package main
import (
"fmt"
. "github.com/logrusorgru/aurora"
)
func main() {
fmt.Println("Hello,", Magenta("Aurora"))
fmt.Println(Bold(Cyan("Cya!")))
}
```
執行後輸出內容如下
![file](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145329039-1236126193.jpg)
## 更多玩法
### 支援格式化輸出函式
除了換行輸出函式外,aurora還支援格式化輸出函式
```go
msg := fmt.Sprintf("My name is %s", Green("pingyeaa"))
fmt.Println(msg)
```
![file](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145329405-807377095.jpg)
### 鏈式呼叫
我們可以巢狀呼叫,來個綠底加粗紅字
```go
fmt.Println(BgGreen(Bold(Red("pingyeaa"))))
```
![file](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145329700-1233953504.jpg)
還可以進行鏈式呼叫,同樣可以達到相同效果,這種方式的可讀性更高一些
```go
fmt.Println(Red("pingyeaa").Bold().BgGreen())
```
### 更簡便的寫法
除了鏈式呼叫外,還有一種更簡便的寫法,就是通過位或運算子來實現
```go
fmt.Println(Colorize("Greeting", GreenFg|RedBg|BoldFm))
```
官方定義了10種常量,感興趣的同學可以自行研究原始碼
```go
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
)
```
同樣也可以搭配鏈式呼叫使用
```go
fmt.Println(Red("x").Colorize(GreenFg))
```
### 支援灰階
所謂灰階,是將最亮與最暗之間的亮度變化,區分為若干份
![file](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145330042-641795417.jpg)
方法中的數字代表灰色深度的數值,支援背景和文字上色
```go
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),
)
```
![file](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145330303-752300491.jpg)
### 支援閃爍
```go
fmt.Println(Blink("Blink"))
```
### 限制
格式化輸出函式中的`%T`與`%p`是沒辦法上色的
```go
r := Red("red")
var i int
fmt.Printf("%T %p\n", r, Green(&i))
```
```shell
aurora.value %!p(aurora.value={0xc42000a310 768 0})
```
但是可以通過在外層巢狀顏色來解決
```go
fmt.Println(Red(fmt.Sprintf("%T %p\n", r, Green(&i))))
```
---
Go語言庫程式碼示例,歡迎star
https://github.com/pingyeaa/golang-examples
---
感謝大家的觀看,如果覺得文章對你有所幫助,歡迎關注公眾號「平也」,聚焦Go語言與技術原理。
![關注我](https://img2020.cnblogs.com/other/1471773/202004/1471773-20200405145332452-363129