These steps cover writing and running your application:
- From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter2/ansicolor.
- Navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter2/ansicolor
You should see a file called go.mod that contains the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter2/ansicolor
- Copy tests from ~/projects/go-programming-cookbook-original/chapter2/ansicolor, or use this as an opportunity to write some of your own code!
- 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)
}
- Create a new directory named example and navigate to it.
- Create a main.go file with the following contents:
package main
import (
"fmt"
"github.com/PacktPublishing/
Go-Programming-Cookbook-Second-Edition/
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())
}
- Run go run main.go.
- You may also run the following commands:
$ go build
$ ./example
- 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...
- If you copied or wrote your own tests, go up one directory and run go test. Ensure that all the tests pass.