Create a load bar in Go

Instead of prepping for interviews I decided to procrastinate and write about a cool piece of code, inspired by a similar example in python found on StackOverflow. We’re going to build a load bar that can show the progress of a program in the terminal.
This will be the end result:
$ go run client.go
Progress [==========================] 1.000000% CompleteFor this project the only imports that we’ll need are fmt, strings, and time in order to display the loader, do strings manipulations, and mimic work being done.
import (
"fmt"
"strings"
"time"
)Let’s jump into the function signature:
func printProgressBar(iteration, total int, prefix, suffix string, length int, fill string) {- iteration — how many jobs have been done
- total — total amount of jobs that must be done
- prefix — the string to appear before the loading bar
- suffix — the string to appear after the loading bar
- length — how long the loading bar is in the terminal window
- fill — what you want to fill the bar with
Next, lets do the calculations needed for our end result. Because Go truncates its division we need to wrap the values in floats. Otherwise, percent would return 0.
...
percent := float64(iteration) / float64(total)
filledLength := int(length * iteration / total)
...Finally, the display. strings.Repeat() allows use to easily fill the bar.
...
end := ">"
if iteration == total {
end = "="
}bar := strings.Repeat(fill, filledLength) + end + strings.Repeat("-", (length-filledLength))
fmt.Printf("\r%s [%s] %f%% %s", prefix, bar, percent, suffix)
if iteration == total {
fmt.Println()
}
...
Putting it all together, along with a driver in main():
package mainimport (
"fmt"
"strings"
"time"
)func printProgressBar(iteration, total int, prefix, suffix string, length int, fill string) {
percent := float64(iteration) / float64(total)
filledLength := int(length * iteration / total)
end := ">"
if iteration == total {
end = "="
}bar := strings.Repeat(fill, filledLength) + end + strings.Repeat("-", (length-filledLength))
fmt.Printf("\r%s [%s] %f%% %s", prefix, bar, percent, suffix)
if iteration == total {
fmt.Println()
}
}func main() {
for i := 0; i < 30; i++ {
time.Sleep(500 * time.Millisecond) // mimics work
printProgressBar(i+1, 30, "Progress", "Complete", 25, "=")
}
}
Progress [=====>--------------------] 0.233333% Complete
Progress [====================>-----] 0.800000% Complete
Progress [==========================] 1.000000% Complete