Here's an example of a progress indicator using ANSI characters in a CLI Go application. This example includes a few different styles of indicators.
package main
import (
"fmt"
"time"
)
// ANSI Color Codes
const (
reset = "\x1b[0m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
cyan = "\x1b[36m"
gray = "\x1b[90m" // Bright black / gray
white = "\x1b[97m"
)
// Progress Bar
func progressBar(current, total int, width int) {
if total <= 0 {
return // Avoid division by zero
}
percent := float64(current) / float64(total)
filledWidth := int(percent * float64(width))
emptyWidth := width - filledWidth
bar := fmt.Sprintf("[%-*s%s%-*s] %.1f%%",
filledWidth, "", // Filled part
gray,
emptyWidth, "", // Empty part
percent*100,
)
fmt.Printf("\r%s%s%s", bar, reset, strings.Repeat(" ", 10)) // Add padding to overwrite longer previous lines
}
// Pac-Man Indicator
func pacManIndicator(current, total int, width int, iteration int) {
if total <= 0 {
return
}
percent := float64(current) / float64(total)
pos := int(percent * float64(width))
pacChar := "C"
if iteration%2 == 0 {
pacChar = "c"
}
dotsCount := width - pos - 1 // -1 for the pacman character itself
if dotsCount < 0 {
dotsCount = 0
}
if pos >= width {
pos = width -1 // Place Pac-Man at the end if 100%
pacChar = "🏁" // Change to a flag at the end
}
bar := fmt.Sprintf("%s %s%s%s%s %.1f%%",
"Pac-Man:",
yellow, // Pac-Man color
strings.Repeat(" ", pos), // Leading spaces
pacChar,
strings.Repeat("·", dotsCount), // Dots to eat (use · or .)
percent*100,
)
fmt.Printf("\r%s%s%s", bar, reset, strings.Repeat(" ", 10))
}
// Spinning Wheel Indicator
func spinningWheelIndicator(iteration int) {
chars := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} // Braille spinner
char := chars[iteration%len(chars)]
fmt.Printf("\r%s %s%s%s", "Spinning:", cyan, char, reset)
}
// Growing Plant Indicator
func growingPlantIndicator(current, total int) {
if total <= 0 {
return
}
percent := float64(current) / float64(total)
stages := []string{"🌱", "🌿", "🌳", "🌲"} // Seedling, herb, deciduous tree, evergreen tree
stageIndex := int(percent * float64(len(stages)))
if stageIndex >= len(stages) {
stageIndex = len(stages) - 1
}
plant := stages[stageIndex]
progress := fmt.Sprintf("%.1f%%", percent*100)
ground := strings.Repeat(" ", 5 - len(progress)/2) // Center the percentage roughly
fmt.Printf("\r%s %s %s %s%s%s", "Growing:", green, plant, ground, progress, reset)
}
func main() {
totalTasks := 100
width := 40 // Width for bar-like indicators
fmt.Println("--- Progress Bar ---")
for i := 0; i <= totalTasks; i++ {
progressBar(i, totalTasks, width)
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nDone.\n") // Newline after completion
fmt.Println("--- Pac-Man Indicator ---")
for i := 0; i <= totalTasks; i++ {
pacManIndicator(i, totalTasks, width, i) // Pass iteration for animation
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nDone.\n")
fmt.Println("--- Spinning Wheel Indicator ---")
// Simulate a short wait
for i := 0; i < 30; i++ { // Run for a fixed number of iterations
spinningWheelIndicator(i)
time.Sleep(100 * time.Millisecond)
}
fmt.Println("\rWaiting: Done. ") // Overwrite spinner and print done message
fmt.Println("\n--- Growing Plant Indicator ---")
for i := 0; i <= totalTasks; i++ {
growingPlantIndicator(i, totalTasks)
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nFully Grown!\n")
fmt.Println("All indicators demonstrated.")
}
Explanation:
- ANSI Constants: Define constants for common colors for readability.
progressBar: A classic bar that changes color based on completion percentage. Uses block (█) and shade (░) characters.
pacManIndicator: Uses spaces, a cycling character (C/c), and dots (·) to create a Pac-Man animation. The iteration parameter helps cycle the Pac-Man mouth.
spinningWheelIndicator: An indeterminate progress indicator using cycling Braille characters. Good for tasks where the total duration isn't known. The iteration cycles through the characters.
growingPlantIndicator: A more conceptual indicator where a plant emoji "grows" through stages based on percentage completion.
main Function: Demonstrates how to use each indicator in a loop, simulating work with time.Sleep. It prints a newline (\n) after each indicator finishes its loop so the next output starts cleanly on a new line.
How to Run:
- Save the code as
progress.go.
- Open your terminal.
- Run it using
go run progress.go.
You should see each indicator animate in place in your terminal!