Skip to content

Instantly share code, notes, and snippets.

@shudipta
Forked from ik5/colors.go
Last active July 28, 2020 00:35
Show Gist options
  • Save shudipta/619733a4179b67b11cbb8f43aa2101c4 to your computer and use it in GitHub Desktop.
Save shudipta/619733a4179b67b11cbb8f43aa2101c4 to your computer and use it in GitHub Desktop.
Simple golang expirement with ANSI colors
package main
// http://play.golang.org/p/jZ5pa944O1 <- will not display the colors
import "fmt"
const (
InfoColor = "\033[1;34m%s\033[0m"
NoticeColor = "\033[1;36m%s\033[0m"
WarningColor = "\033[1;33m%s\033[0m"
ErrorColor = "\033[1;31m%s\033[0m"
DebugColor = "\033[0;36m%s\033[0m"
)
func color0() {
fmt.Printf(InfoColor, "Info")
fmt.Println("")
fmt.Printf(NoticeColor, "Notice")
fmt.Println("")
fmt.Printf(WarningColor, "Warning")
fmt.Println("")
fmt.Printf(ErrorColor, "Error")
fmt.Println("")
fmt.Printf(DebugColor, "Debug")
fmt.Println("\n============")
for i := 0; i < 100; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("(%d, %d) ---> \033[%d;%dm%s\033[m\n",
j, i, // (j, i) pair
j, i, "MY_TEXT")
}
fmt.Println("============")
}
}
@shudipta
Copy link
Author

shudipta commented Apr 24, 2020

@maxmcd => https://gist.github.com/ik5/d8ecde700972d4378d87#gistcomment-2861543

Also:

package main

import "fmt"

const (
	PrintColor = "\033[38;5;%dm%s\033[39;49m\n"
)

func main() {
	for j := 0; j < 256; j++ {
		fmt.Printf(PrintColor, j, "Hello!")
	}
}

@shudipta
Copy link
Author

shudipta commented Apr 24, 2020

@zaydek => https://gist.github.com/ik5/d8ecde700972d4378d87#gistcomment-3074524

I built on this, changed a few small things:

package main

import "fmt"

var (
  Info = Teal
  Warn = Yellow
  Fata = Red
)

var (
  Black   = Color("\033[1;30m%s\033[0m")
  Red     = Color("\033[1;31m%s\033[0m")
  Green   = Color("\033[1;32m%s\033[0m")
  Yellow  = Color("\033[1;33m%s\033[0m")
  Purple  = Color("\033[1;34m%s\033[0m")
  Magenta = Color("\033[1;35m%s\033[0m")
  Teal    = Color("\033[1;36m%s\033[0m")
  White   = Color("\033[1;37m%s\033[0m")
)

func Color(colorString string) func(...interface{}) string {
  sprint := func(args ...interface{}) string {
    return fmt.Sprintf(colorString,
      fmt.Sprint(args...))
  }
  return sprint
}

func main() {
  fmt.Println(Info("hello, world!"))
}

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment