Created
February 18, 2019 18:39
-
-
Save meysampg/2ee10820e93987f75e9b87540194ccdb to your computer and use it in GitHub Desktop.
Show a progress bar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
const total = 5 * time.Second | |
type process struct { | |
step time.Duration | |
total time.Duration | |
} | |
type processes map[int]*process | |
func main() { | |
var currentProcesses = make(processes) | |
var progressBar = make(chan int, len(currentProcesses)) | |
currentProcesses.AddProcess(1, total) | |
currentProcesses.AddProcess(2, total) | |
currentProcesses.AddProcess(3, total) | |
go writeOutput(progressBar, currentProcesses) | |
progressBar <- 1 | |
progressBar <- 2 | |
progressBar <- 3 | |
go updateProgressBar(progressBar, currentProcesses, 1, 1000*time.Millisecond) | |
go updateProgressBar(progressBar, currentProcesses, 2, 500*time.Millisecond) | |
go updateProgressBar(progressBar, currentProcesses, 3, 100*time.Millisecond) | |
time.Sleep(10 * time.Second) | |
} | |
func (p processes) AddProcess(id int, total time.Duration) { | |
p[id] = &process{total: total} | |
} | |
func (p *process) UpdateProcess(step time.Duration) { | |
p.step = step | |
} | |
func updateProgressBar(progressBar chan<- int, currentProcesses processes, id int, step time.Duration) { | |
steps := int(currentProcesses[id].total) / int(step) | |
for i := 0; i < steps; i++ { | |
time.Sleep(step) | |
currentProcesses[id].UpdateProcess(time.Duration((i+1) * int(step))) | |
progressBar <- id | |
} | |
} | |
func writeOutput(progressBar <-chan int, currentProcesses processes) { | |
for { | |
x := <-progressBar | |
s := "" | |
for _, process := range currentProcesses { | |
s += outputProgress(x, int(process.step), int(process.total)) | |
} | |
fmt.Printf("\033[0;0H") | |
fmt.Print(s) | |
} | |
} | |
func outputProgress(id int, step, total int) string { | |
current := percent(step, total) | |
s := fmt.Sprintf("Doing Task %d [", id) | |
for i := 0; i < current; i++ { | |
s += "=" | |
} | |
for i := current; i < 100; i++ { | |
s += " " | |
} | |
s += fmt.Sprintf("] %d%%\r\n", current) | |
return s | |
} | |
func percent(step, total int) int { | |
return int(float32(step) / float32(total) * 100) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment