Color lets you use colorized outputs in terms of ANSI Escape Codes in Go (Golang)

color PkgGoDev

Color lets you use colorized outputs in terms of ANSI Escape Codes in Go (Golang). It has support for Windows too! The API can be used in several ways, pick one that suits you.

Color

Install

go get github.com/SensioX/utilities

Examples

Standard colors

// Print with default helper functions
color.Cyan("Prints text in cyan.")

// A newline will be appended automatically
color.Blue("Prints %s in blue.", "text")

// These are using the default foreground colors
color.Red("We have red")
color.Magenta("And many others ..")

Mix and reuse colors

// Create a new color object
c := color.New(color.FgCyan).Add(color.Underline)
c.Println("Prints cyan text with an underline.")

// Or just add them to New()
d := color.New(color.FgCyan, color.Bold)
d.Printf("This prints bold cyan %s\n", "too!.")

// Mix up foreground and background colors, create new mixes!
red := color.New(color.FgRed)

boldRed := red.Add(color.Bold)
boldRed.Println("This will print text in bold red.")

whiteBackground := red.Add(color.BgWhite)
whiteBackground.Println("Red text with white background.")

Use your own output (io.Writer)

// Use your own io.Writer output
color.New(color.FgBlue).Fprintln(myWriter, "blue color!")

blue := color.New(color.FgBlue)
blue.Fprint(writer, "This will print text in blue.")

Custom print functions (PrintFunc)

// Create a custom print function for convenience
red := color.New(color.FgRed).PrintfFunc()
red("Warning")
red("Error: %s", err)

// Mix up multiple attributes
notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
notice("Don't forget this...")

Custom fprint functions (FprintFunc)

blue := color.New(color.FgBlue).FprintfFunc()
blue(myWriter, "important notice: %s", stars)

// Mix up with multiple attributes
success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
success(myWriter, "Don't forget this...")

Insert into noncolor strings (SprintFunc)

// Create SprintXxx functions to mix strings with other non-colorized strings:
yellow := color.New(color.FgYellow).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))

info := color.New(color.FgWhite, color.BgGreen).SprintFunc()
fmt.Printf("This %s rocks!\n", info("package"))

// Use helper functions
fmt.Println("This", color.RedString("warning"), "should be not neglected.")
fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.")

// Windows supported too! Just don't forget to change the output to color.Output
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))

Plug into existing code

// Use handy standard colors
color.Set(color.FgYellow)

fmt.Println("Existing text will now be in yellow")
fmt.Printf("This one %s\n", "too")

color.Unset() // Don't forget to unset

// You can mix up parameters
color.Set(color.FgMagenta, color.Bold)
defer color.Unset() // Use it in your function

fmt.Println("All text will now be bold magenta.")

Disable/Enable color

There might be a case where you want to explicitly disable/enable color output. the go-isatty package will automatically disable color output for non-tty output streams (for example if the output were piped directly to less).

The color package also disables color output if the NO_COLOR environment variable is set (regardless of its value).

Color has support to disable/enable colors programatically both globally and for single color definitions. For example suppose you have a CLI app and a --no-color bool flag. You can easily disable the color output with:

var flagNoColor = flag.Bool("no-color", false, "Disable color output")

if *flagNoColor {
	color.NoColor = true // disables colorized output
}

It also has support for single color definitions (local). You can disable/enable color output on the fly:

c := color.New(color.FgCyan)
c.Println("Prints cyan text")

c.DisableColor()
c.Println("This is printed without any color")

c.EnableColor()
c.Println("This prints again cyan...")

GitHub Actions

To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set color.NoColor = false so that it bypasses the check for non-tty output streams.

Todo

  • Save/Return previous values
  • Evaluate fmt.Formatter interface

Credits

License

The MIT License (MIT) - see LICENSE.md for more details

Similar Resources

Wl-gammarelay - Wayland utility for changing color temperature using hotkeys

wl-gammarelay This utility was developed from gammastep, a fork of redshift as w

Nov 20, 2022

A color manipulation and conversion library for Go. 🌈 ✨

Khroma Khroma is a color manipulation and conversion library for Go. ✨ 🌈 Example package main import ( "log" "github.com/qbee-org/khroma" ) func

May 30, 2022

Use Golang to implement PHP's common built-in functions.

PHP2Go Use Golang to implement PHP's common built-in functions. About 140+ functions have been implemented. Install go get github.com/syyongx/php2go R

Dec 28, 2022

Easy to use, light enough, good performance Golang library

 Easy to use, light enough, good performance Golang library

指令使用 特性 简单易用、足够轻量,避免过多的外部依赖,最低兼容 Window 7 等老系统 快速上手 安装 $ go get github.com/sohaha/zlsgo HTTP 服务 // main.go

Dec 29, 2022

Procswap is a simple application that allows you to prioritize processes on a Windows machine.

Procswap is a simple application that allows you to prioritize processes on a Windows machine.

Procswap is a simple application that allows you to prioritize processes on a Windows machine.

Mar 8, 2022

cuckoo-filter go implement. config by you 布谷鸟过滤器的Go实现,可以定制化过滤器参数

Cuckoo filter is a Bloom filter replacement for approximated set-membership queries. While Bloom filters are well-known space-efficient data structures to serve queries like "if item x is in a set?", they do not support deletion. Their variances to enable deletion (like counting Bloom filters) usually require much more space.

Jan 1, 2023

go-i18n is a Go package and a command that helps you translate Go programs into multiple languages.

go-i18n is a Go package and a command that helps you translate Go programs into multiple languages.

Jan 2, 2023

this is an api that execute your deno code and send you the output

this a simple api that execute your deno code and send you the output, has not limit per request example request: in deno: const rawResponse = await f

Dec 23, 2022

Clean-Swift source and test code auto-generator. It can save you time typing 500-600 lines of code.

Clean-Swift source and test code auto-generator. It can save you time typing 500-600 lines of code.

Clean-Swift source & test code auto generator Overview Run Output Basic Usage make config.yaml target_project_name: Miro // target project name copyri

Apr 13, 2022
Related tags
Simple library to handle ANSI functions and parsing of color formatting strings

Emerald A basic color library for use in my Go projects, built on top of mgutz/ansi. Package ansi is a small, fast library to create ANSI colored stri

Oct 28, 2022
COCO (Color Converter) is a color conversion library for Go.

COCO (Color Converter) for Go COCO (Color Converter) is a color conversion library for Go. Heavily inspired by NPM's color-convert. It converts all wa

Oct 4, 2022
Easy to use open source hardware to drive WS2811 LEDs with high-quality color

STOP DOING FADECANDY LEDs were not supposed to be given data pins YEARS of "temporal dithering" but no real-world use found for having more than three

Dec 29, 2022
EGo lets you build, debug und run Go apps on Intel SGX - as simple as conventional Go programming!

EGo lets you build, debug und run Go apps on Intel SGX - as simple as conventional Go programming!

Dec 28, 2022
Calling functions by name and getting outputs by using reflect package.

Invoker A library to call (invoke) functions by taking names and sample inputs of those functions as parameters. And returns the types and values of o

Dec 20, 2021
A library for parsing ANSI encoded strings
 A library for parsing ANSI encoded strings

Go ANSI Parser converts strings with ANSI escape codes into a slice of structs that represent styled text

Sep 20, 2022
Raw ANSI sequence helpers

Raw ANSI sequence helpers

Oct 23, 2022
Color generator with golang
Color generator with golang

color-generator How to use this repo <img src="https://color-pallete-gen.herokuapp.com/hexCode" /> Like this: Getting Started Copy sample.env to .env

Oct 22, 2021
Toolkits Codes Based on Go.

Toolkits Codes Based on Go.

Nov 2, 2022
Go package to generate and manage color palettes & schemes 🎨
Go package to generate and manage color palettes & schemes 🎨

Go package to generate and manage color palettes & schemes

Dec 29, 2022