📚Cheatsheets

Cheatsheet collection for go, rust and javascript.

How to print colored text in Go?

Create this module.

package color

import "fmt"

const escape = "\x1b"

const (
	NONE = iota
	RED
	GREEN
	YELLOW
	BLUE
	PURPLE
)

func color(c int) string {
	if c == NONE {
		return fmt.Sprintf("%s[%dm", escape, c)
	}

	return fmt.Sprintf("%s[3%dm", escape, c)
}

func Format(c int, text string) string {
	return color(c) + text + color(NONE)
}

If you are on windows add this file to enable printing colored text in terminal.

// +build windows
package color

import (
	"os"

	"golang.org/x/sys/windows"
)

func init() {
	stdout := windows.Handle(os.Stdout.Fd())
	var originalMode uint32

	windows.GetConsoleMode(stdout, &originalMode)
	windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
}

Now you can use it like this.

func main() {
	println(color.Format(color.RED, "I'm red!"))
	println(color.Format(color.BLUE, "I'm blue!"))
	println(color.Format(color.GREEN, "I'm green!"))
	println(color.Format(color.YELLOW, "I'm yellow!"))
	println(color.Format(color.PURPLE, "I'm purple!"))
}

See other cheatsheet's here