A lightweight Go library for terminal text colorization using ANSI escape codes.
- Simple and intuitive API
- Support for multiple color schemes (basic, bright, background colors)
- Memory efficient with sync.Pool buffer management
- High-performance operations with zero external dependencies
- Compatible with any io.Writer interface
go get github.com/yanun0323/colorizepackage main
import (
"fmt"
"strings"
"github.com/yanun0323/colorize"
)
func main() {
// Basic string colorization
fmt.Println(colorize.String(colorize.ColorRed, "Error message"))
fmt.Println(colorize.Sprint(colorize.ColorGreen, "Success:", " operation completed"))
fmt.Println(colorize.Sprintf(colorize.ColorBlue, "User %s logged in", "john"))
// Write to buffer
var buf strings.Builder
colorize.Fprint(&buf, colorize.ColorYellow, "Warning:", " low disk space")
colorize.Fprintf(&buf, colorize.ColorCyan, " Available: %d%%", 15)
fmt.Print(buf.String())
// Remove ANSI codes
coloredText := colorize.String(colorize.ColorRed, "Error")
plainText := colorize.Reset(coloredText)
fmt.Println(plainText) // Output: "Error" (without colors)
}For maximum performance, you can build the colored output by appending to a pre-allocated byte slice:
buf := make([]byte, 0, 4<<10) // allocate enough size
buf = append(buf, colorize.ColorRed...)
buf = append(buf, "Hello, World"...)
buf = append(buf, colorize.ColorReset...)String(c Color, str ...string) string- Colorize multiple stringsSprint(c Color, args ...any) string- Colorize with fmt.Sprint behaviorSprintf(c Color, format string, args ...any) string- Colorize with formattingFprint(w io.Writer, c Color, args ...any) (int, error)- Write colorized text to writerFprintf(w io.Writer, c Color, format string, args ...any) (int, error)- Write formatted colorized textReset(s string) string- Remove ANSI escape codes from string
Benchmarks (darwin/arm64, Apple M2).
BenchmarkColorizeString-8 39335316 30.01 ns/op 24 B/op 1 allocs/op
BenchmarkColorizeReset-8 25729447 45.86 ns/op 16 B/op 1 allocs/op
BenchmarkColorizeSprint-8 14059197 80.54 ns/op 136 B/op 3 allocs/op
BenchmarkColorizeSprintf-8 14723767 81.97 ns/op 136 B/op 3 allocs/op
BenchmarkColorizeFprint-8 36809578 33.07 ns/op 0 B/op 0 allocs/op
BenchmarkColorizeFprintf-8 34705401 35.12 ns/op 0 B/op 0 allocs/op
BenchmarkColorizeAppend-8 634096282 1.89 ns/op 0 B/op 0 allocs/opThis project is licensed under the MIT License - see the LICENSE file for details.
