How Can I used 256 colors in terminal with Golang.
As Libraries like faith/color only have limited colors support.
This python library here
use some kind of default code and a color code to print colored text in terminal.
I try to use color code but instead of color it printing color code in go program but in python program it prints colored text.
How can I print color use color code as above library doing...
Do I need to initialize the terminal ? If yes How?
Thanks!
I am expecting 256 colors to print in terminal.
*go version: 1.18.7
CodePudding user response:
Windows can be weird. In some cases you need to set the console mode. If you are using Windows, specify it as part of your question.
colors.go
:
package main
import (
"fmt"
"strconv"
)
func main() {
setConsoleColors()
for i := 0; i < 16; i {
for j := 0; j < 16; j {
code := strconv.Itoa(i*16 j)
color := "\u001b[38;5;" code "m"
fmt.Printf("%s %-4s", color, code)
}
fmt.Println()
}
fmt.Print("\u001b[0m")
}
colors_windows.go
:
//go:build windows
package main
import "golang.org/x/sys/windows"
func setConsoleColors() error {
console := windows.Stdout
var consoleMode uint32
windows.GetConsoleMode(console, &consoleMode)
consoleMode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
return windows.SetConsoleMode(console, consoleMode)
}
colors_other.go
:
//go:build !windows
package main
func setConsoleColors() error {
return nil
}