Go如何輸出ANSI 顏色代碼

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

這連天bee升級到了1.5版本,在執行bee version的時候會輸出一個有顏色的BEE的logo,很多人覺著很神奇,其實這個就是ANSI顏色代碼。

其實在Linux,我們編寫C語言輕易可以實現這個效果。

具體的書寫格式如下:

格式:\033[顯示方式;前景色彩;背景色m 說明:前景色彩            背景色           顏色---------------------------------------30                40              黑色31                41              紅色32                42              綠色33                43              黃色34                44              藍色35                45              紫紅色36                46              青藍色37                47              白色顯示方式           意義-------------------------0                終端預設設定1                高亮顯示4                使用底線5                閃爍7                反白顯示8                不可見 例子:\033[1;31;40m    \033[0m          

詳細資料,請參看https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

但是在windows下就比較難做到。

The Win32 console did not support ANSI escape sequences at all until Windows 10 "Threshold 2".[10] Some replacements or additions for the console window such as JP Software's TCC (formerly 4NT), Michael J. Mefford's ANSI.COM, Jason Hood's ANSICON[11] and Maximus5's ConEmu do interpret ANSI escape sequences printed by programs.

從這段可以看出win 10才支援。

內事不明問百度,外事不清問Google。搜尋到https://github.com/fatih/color這個神器。

go get github.com/fatih/color

下面我就模仿bee寫一個小程式。

package mainimport ("fmt""github.com/fatih/color")func main() {beeStrUp := `______| ___ \| |_/ /  ___   ___| ___ \ / _ \ / _ \| |_/ /|  __/|  __/\____/  \___| \___| v1.5.0`beeStrDown := `├── Beego     : 1.7.0├── GoVersion : go1.6.2├── GOOS      : windows├── GOARCH    : amd64├── NumCPU    : 8├── GOPATH    : x:\Eagle\go├── GOROOT    : y:\Go\├── Compiler  : gc└── Date      : Friday, 19 Aug 2016`color.Set(color.FgMagenta, color.Bold)defer color.Unset()fmt.Println(beeStrUp)color.Set(color.FgGreen, color.Bold)fmt.Println(beeStrDown)}

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.