Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: How to color fmt.Fprintf output?

Tags:

go

I know I can add colors to fmt.Println output with something like:

package main

import (
    "fmt"
)

func main() {
    colorReset := "\033[0m"
    colorRed := "\033[31m"
    fmt.Println(string(colorRed), "test", string(colorReset))
    fmt.Println("next")
}

Is there any way to colorize the output of fmt.Fprintf?

like image 585
Alex Cohen Avatar asked Aug 31 '25 16:08

Alex Cohen


2 Answers

In the same way you used the Println you can use colors with Fprintf, ex

const colorRed = "\033[0;31m"
const colorNone = "\033[0m"

func main() {
    fmt.Fprintf(os.Stdout, "Red: \033[0;31m %s None: \033[0m %s", "red string", "colorless string")
    fmt.Fprintf(os.Stdout, "Red: %s %s None: %s %s", colorRed, "red string", colorNone, "colorless string")
}
like image 84
Jhonatan Avatar answered Sep 03 '25 00:09

Jhonatan


There was a color package published in November 2023 that makes this pretty easy and expandable with a lot of cool options:

https://pkg.go.dev/github.com/fatih/color

For example:

c := color.New(color.FgCyan)
c.Println("Prints cyan text")

Or

blue := color.New(color.FgBlue)
blue.Fprint(myWriter, "This will print text in blue.")
like image 25
dalewb Avatar answered Sep 03 '25 00:09

dalewb