Skip to Content
Course content

216: Colorized Terminal Output

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I actually make text change color in the terminal?

At the end of the day, your terminal isn't "smart"β€”it's just reading a stream of characters. To change colors, we send it something called ANSI escape codes. These are special sequences of characters that the terminal intercepts and interprets as formatting commands rather than literal text to be printed.

The most common pattern starts with \033[ (the escape character) followed by a color code and ending with m. But here is the catch: once you tell the terminal to start printing in red, it will stay red forever until you explicitly tell it to go back to normal using the "reset" code.

package main

import "fmt"

func main() {
    // \033[31m is Red
    // \033[32m is Green
    // \033[0m is the Reset code
    fmt.Println("\033[31mThis is a critical error!\033[0m")
    fmt.Println("\033[32mSystem is healthy.\033[0m")
}

Do I really have to memorize those weird escape codes?

Absolutely not. I've seen too many developers hardcode \033[31m all over their codebase, and it becomes a nightmare to read. Instead, I always suggest defining your own internal "palette" using constants. This makes your code self-documenting and lets you change the color scheme in one place if you decide you hate that specific shade of yellow.

Here is how I usually set this up for a small CLI tool:

package main

import "fmt"

const (
    ColorReset  = "\033[0m"
    ColorRed    = "\033[31m"
    ColorGreen  = "\033[32m"
    ColorYellow = "\033[33m"
    ColorBlue   = "\033[34m"
)

func main() {
    status := "Offline"
    color := ColorRed

    if status == "Online" {
        color = ColorGreen
    }

    fmt.Printf("Server Status: %s%s%s\n", color, status, ColorReset)
}

Will this work for everyone who downloads my tool?

Mostly, but not always. Most modern terminals (macOS, Linux, and the newer Windows Terminal) handle ANSI codes perfectly. However, older Windows CMD prompts or certain CI/CD pipeline logs might just print the raw characters, leaving your users with a mess of [31m junk in their output.

If you're building a professional-grade tool, don't reinvent the wheel. I highly recommend the fatih/color library. It's the industry standard for Go because it detects the user's terminal capabilities automatically. If the terminal doesn't support color, the library just strips the codes out so the output remains clean. It also handles the "NO_COLOR" environment variable standard, which is a polite way to let users opt-out of colors if they have visual impairments or are piping your output to a text file.

If you're just building something for yourself or a internal script, the constants approach I showed you is more than enough. But for public tools? Go with a library.




πŸ“‹ Practical Task

Build a Color-Coded Log Level Formatter

Create a program that simulates a system logger. You need to write a function called formatLog that takes two arguments: a log level (string) and the message (string).

  • If the level is "INFO", the level tag should be Blue.
  • If the level is "WARN", the level tag should be Yellow.
  • If the level is "ERROR", the level tag should be Red.
  • Any other level should be printed in the default terminal color.

Your output should look like this: [INFO] Connection established (where [INFO] is blue).

Make sure you properly reset the color after the tag so that the actual message is printed in the default terminal color.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.