Go Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

These steps cover writing and running your application:

  1. From your terminal/console application, create and navigate to the chapter2/ansicolor directory.
  2. Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter2/ansicolor, or use this as an exercise to write some of your own code!
  3. Create a file called color.go with the following contents:
        package ansicolor

import "fmt"

//Color of text
type Color int

const (
// ColorNone is default
ColorNone = iota
// Red colored text
Red
// Green colored text
Green
// Yellow colored text
Yellow
// Blue colored text
Blue
// Magenta colored text
Magenta
// Cyan colored text
Cyan
// White colored text
White
// Black colored text
Black Color = -1
)

// ColorText holds a string and its color
type ColorText struct {
TextColor Color
Text string
}

func (r *ColorText) String() string {
if r.TextColor == ColorNone {
return r.Text
}

value := 30
if r.TextColor != Black {
value += int(r.TextColor)
}
return fmt.Sprintf("33[0;%dm%s33[0m", value, r.Text)
}
  1. Create a new directory named example.
  2. Navigate to example.
  3. Create a main.go file with the following contents and ensure that you modify the ansicolor import to use the path you set up in step 1:
        package main

import (
"fmt"

"github.com/agtorre/go-cookbook/chapter2/ansicolor"
)

func main() {
r := ansicolor.ColorText{
TextColor: ansicolor.Red,
Text: "I'm red!",
}

fmt.Println(r.String())

r.TextColor = ansicolor.Green
r.Text = "Now I'm green!"

fmt.Println(r.String())

r.TextColor = ansicolor.ColorNone
r.Text = "Back to normal..."

fmt.Println(r.String())
}
  1. Run go run main.go.
  1. You may also run these commands:
      go build
./example
  1. You should see the following output with the text colored if your terminal supports the ANSI coloring format:
      $ go run main.go
I'm red!
Now I'm green!
Back to normal...
  1. If you copied or wrote your own tests, go up one directory and run go test. Ensure all tests pass.