Many articles on bash suggest using something that looks like \e[39m
for pretty colors, and while these work
just fine with bash, it’s a different story with Go – the string is just rendered as is.
Yet, there’s a few libraries that allow you to color your outputs, yet the code is so bloated you can’t even get
an answer to the problem you’re trying to fix.
Not everybody wants to import a library merely for colors, after all.
And so, I bring you the simplest method to color your console:
package color
import "runtime"
var Reset = "\033[0m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var Purple = "\033[35m"
var Cyan = "\033[36m"
var Gray = "\033[37m"
var White = "\033[97m"
func init() {
if runtime.GOOS == "windows" {
Reset = ""
Red = ""
Green = ""
Yellow = ""
Blue = ""
Purple = ""
Cyan = ""
Gray = ""
White = ""
}
}
As you may know, Windows doesn’t support colors in its command line out of the box, therefore, checking
for the runtime in an init
and setting all colors to an empty string if the runtime is windows
will
fix this issue without printing ugly characters all over your console.
Clearly, there are ways of making it work on the good ol’ command prompt, but since Windows 10’s WSL (Windows Subsystem for Linux) is a thing, you can just use that if you want pretty colors without the need to struggle.
All you have to do is prepend the text you wish to color with color.YOUR_COLOR
and add color.Reset
at the end of the same text. If you don’t reset the color using Color.Reset
,
your console/terminal will stay that same color for the rest of the session, so don’t forget it.
func main() {
println(color.White + "This is White" + color.Reset)
println(color.Red + "This is Red" + color.Reset)
println(color.Green + "This is Green" + color.Reset)
println(color.Yellow + "This is Yellow" + color.Reset)
println(color.Blue + "This is Blue" + color.Reset)
println(color.Purple + "This is Purple" + color.Reset)
println(color.Cyan + "This is Cyan" + color.Reset)
println(color.Gray + "This is Gray" + color.Reset)
}
If you’d rather use a library instead, you can have a look at TwiN/go-color, which is a very lightweight library I made after growing tired of re-implementing the same thing in several projects:
package main
import "github.com/TwiN/go-color"
func main() {
println(color.Ize(color.Red, "This is red"))
// Or if you prefer the longer version
println(color.Colorize(color.Red, "This is also red"))
}