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.

Go Programming World
Go Programming World
Go Programming World
Using Go's fatih/color Package to Output Colored Text in the Terminal

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CLIGoterminalANSIcolorfatih/color
Go Programming World
Written by

Go Programming World

Mobile version of tech blog https://jianghushinian.cn/, covering Golang, Docker, Kubernetes and beyond.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.