Last active
February 17, 2021 12:42
-
-
Save sajadko/028748ec62b6b40b88632b731ff22337 to your computer and use it in GitHub Desktop.
Absolute Position ProgressBar Golang (With Colors)
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" | |
"math" | |
"strconv" | |
"time" | |
"github.com/gookit/color" | |
) | |
type barTheme struct { | |
first string | |
progress string | |
progresshead string | |
last string | |
mainColor string | |
midColor string | |
midheadColor string | |
} | |
//ProgressBar main type | |
type ProgressBar struct { | |
theme barTheme | |
current int | |
max int | |
before string | |
beforeEveryLine string | |
} | |
//Default is the constructor | |
func (bar ProgressBar) Default(max int, before string) ProgressBar { | |
var defaultBar barTheme = barTheme{ | |
first: "[", | |
progress: "=", | |
progresshead: ">", | |
last: "]", | |
mainColor: "#ffffff", | |
midColor: "#b5bd68", | |
midheadColor: "#00fff3", | |
} | |
bar = ProgressBar{ | |
theme: defaultBar, | |
current: 0, | |
max: max, | |
before: before, | |
beforeEveryLine: "", | |
} | |
return bar | |
} | |
func (bar *ProgressBar) render() { | |
var percent = (float64(bar.current) / float64(bar.max)) * float64(100) | |
// fmt.Println("current : " + strconv.Itoa(bar.current)) | |
var progress = (float64(bar.current) / float64(bar.max)) * float64(50) | |
var passed = progress | |
var passedInt = int(math.Floor(passed)) | |
var remaining = float64(50) - passed | |
var remainingInt = int(math.Floor(remaining)) | |
fmt.Print("\033[2K\033[1G") | |
if percent == 100 { | |
bar.theme.progresshead = "=" | |
} | |
if bar.beforeEveryLine != "" { | |
fmt.Println(bar.beforeEveryLine) | |
} | |
fmt.Print(bar.before) | |
color.HEX(bar.theme.mainColor).Print(bar.theme.first) | |
for i := 0; i < passedInt; i++ { | |
color.HEX(bar.theme.midColor).Print(bar.theme.progress) | |
} | |
if percent == 100 { | |
color.HEX(bar.theme.midColor).Print(bar.theme.progress) | |
} else { | |
color.HEX(bar.theme.midheadColor).Print(bar.theme.progresshead) | |
} | |
for j := 0; j < remainingInt; j++ { | |
fmt.Print(" ") | |
} | |
color.HEX(bar.theme.mainColor).Print(bar.theme.last) | |
} | |
//Add adds the input value to progress | |
func (bar *ProgressBar) Add(value int, beforeEveryLine string) { | |
bar.beforeEveryLine = beforeEveryLine | |
bar.current = bar.current + 1 | |
bar.render() | |
} | |
func main() { | |
mybar := new(ProgressBar).Default(100, "Loading : ") | |
for i := 0; i < 100; i++ { | |
var beforLineText = "Line " + strconv.Itoa(i) | |
time.Sleep(1 * time.Second) | |
mybar.Add(1, beforLineText) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment