Using Go's fatih/color Package to Output Colored Text in the Terminal
This article explains how to add colors to terminal output using the Go language, introduces the fatih/color package with practical code examples, demonstrates mixing colors, writing to files, building a Cobra-based CLI demo, and details the underlying ANSI escape sequence mechanism.
This tutorial shows how to enhance terminal output with colors using Go, focusing on the fatih/color package.
After importing the package, simple functions like color.Cyan("Prints text in cyan.") , color.Blue("Prints %s in blue.", "text") , and color.Red("Prints text in red.") produce colored text, as demonstrated by the provided example code and screenshots.
The library also supports attributes such as underline and bold by creating color objects, e.g., c := color.New(color.FgCyan).Add(color.Underline) and using c.Println("Prints cyan text with an underline.") , or combining foreground and background colors like red := color.New(color.FgRed); whiteBackground := red.Add(color.BgWhite); whiteBackground.Println("Red text with white background.") .
Output can be directed to any io.Writer , allowing logs to be written to files with color codes, as shown in the file‑writing example where color.New(color.FgBlue).Fprintln(f, "blue color!") writes colored text to output.log .
A practical CLI demo named lscolor is built with Cobra, listing directories with cyan for folders and white for files, illustrating how to integrate fatih/color into real command‑line tools.
The article then explains the underlying ANSI escape sequence mechanism: the ESC character ( \e or \033 ) starts a control sequence ( \e[ ), followed by parameters like color code (e.g., 34 for blue) and text decoration, ending with m . Resetting attributes uses \e[0m .
Finally, the guide summarizes that readers can now output colored characters in Go terminals and understand the ANSI escape logic, with links to source code and further reading.
Go Programming World
Mobile version of tech blog https://jianghushinian.cn/, covering Golang, Docker, Kubernetes and beyond.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.