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
?
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")
}
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.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With