progressbar

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2025 License: MIT Imports: 15 Imported by: 1

README

progressbar

A modern, customizable, concurrent-safe progress bar library for Go (Golang).
Supports dynamic terminal width detection, templating, byte-size formatting, speed calculation, ETA, additional info, and works seamlessly with io.Reader.

GoDev

Features

  • Fully customizable template using Go's text/template
  • Automatic terminal width detection (Windows + Unix)
  • Byte size formatting (1.23 MB, 45.6 KiB/s, etc.)
  • Accurate speed calculation (total + interval-based)
  • ETA / Time left with animated "calculating..." dots
  • Additional dynamic text support
  • Message channel for temporary notifications
  • Concurrent-safe – multiple goroutines can call Add() safely
  • Generic – works with int or int64 totals
  • io.Reader integration via FromReader()
  • Cancelable with graceful "Cancelled" output

Installation

go get github.com/sunshineplan/progressbar

Quick Start

package main

import (
    "os"
    "time"

    "github.com/sunshineplan/progressbar"
)

func main() {
    // Create a progress bar with total = 1000
    pb := progressbar.New(1000)

    // Optional customizations
    pb.SetWidth(50).
       SetRefreshInterval(2 * time.Second).
       SetRenderInterval(100 * time.Millisecond)

    // Start rendering
    if err := pb.Start(); err != nil {
        panic(err)
    }

    // Simulate work
    for i := 0; i < 1000; i++ {
        pb.Add(1)
        pb.Additional("processing user #" + string(rune(i+1)))
        time.Sleep(5 * time.Millisecond)
    }

    // Wait for completion (optional if you want to block)
    pb.Wait()
}

Beautiful Adaptive Output (example)

[=========================>                  ]  15.67 MB/s  784.20 MB(78.42%) of 1.00 GB [downloading chunk 89]  Elapsed: 50s  Left: 14s

When terminal is narrow, it gracefully degrades to shorter formats, and finally to just the bar + additional text.

Customization

pb.SetRender(func(w io.Writer, f progressbar.Frame) {
    fmt.Fprintf(w, "[%s] %.1f%% %s/s",
        progressbar.Bar(f.Current, f.Total, f.BarWidth),
        progressbar.Percent(f.Current, f.Total),
        progressbar.Speed(f.Speed, f.Unit),
    )
})
Or Custom Template (Advanced)
pb.SetTemplate(template.Must(template.New("").Funcs(progressbar.DefaultFuncMap()).Parse(`[{{bar .Current .Total .BarWidth}}] {{percent .Current .Total | printf "%.1f%%"}} {{speed .Speed .Unit}}`)))
Byte Downloads (with io.Reader)
pb := progressbar.New(totalBytes)
pb.SetUnit("bytes") // enables ByteSize formatting

pb.FromReader(http.Body, os.Stdout) // starts automatically, returns written bytes
Display Temporary Messages
pb.Message("Downloading update...")
time.Sleep(2 * time.Second)
pb.Message("Verifying checksum...")
Cancel Gracefully
go func() {
    time.Sleep(10 * time.Second)
    pb.Cancel() // prints "\nCancelled\n"
}()

API Reference

// Creation
pb := progressbar.New[T int|int64](total T) *ProgressBar[T]

// Configuration
pb.SetWidth(width int)
pb.SetRefreshInterval(d time.Duration) // speed calculation interval
pb.SetRenderInterval(d time.Duration)  // UI refresh rate
pb.SetRender(fn func(w io.Writer, f Frame)) error
pb.SetTemplate(t *template.Template) error
pb.SetUnit(unit string)               // "bytes" enables ByteSize, otherwise numeric

// Runtime
pb.Start() error
pb.Add(n T)
pb.Additional(text string)
pb.Message(msg string) error
pb.Total() int64
pb.Current() int64
pb.Elapsed() time.Duration
pb.Speed() float64
pb.Wait()
pb.Cancel()

// io.Reader helper
pb.FromReader(r io.Reader, w io.Writer) (written int64, err error)

// template helper functions
progressbar.Bar(current, total int64, width int) string
progressbar.Format(n int64, unit string) string
progressbar.Percent(current, total int64) float64
progressbar.Speed(v float64, unit string) string
progressbar.Left(current, total int64, speed float64) time.Duration

License

MIT © SunshinePlan


Enjoy a clean, informative progress bar in your CLI tools!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultRenderFunc = func(w io.Writer, f Frame) {
	winsize := GetWinsize()
	n := winsize - f.BarWidth - len(f.Additional)
	switch {
	case n >= 60:
		defaultTemplate.ExecuteTemplate(w, "full", f)
	case n >= 40:
		defaultTemplate.ExecuteTemplate(w, "standard", f)
	case n >= 20:
		defaultTemplate.ExecuteTemplate(w, "lite", f)
	case n > 5 && len(f.Additional) > 0:
		defaultTemplate.ExecuteTemplate(w, "mini", f)
	default:
		width := winsize - 5
		w.Write([]byte("["))
		if f.Current == f.Total {
			w.Write([]byte(strings.Repeat("=", width)))
		} else {
			done := int(float64(width) * float64(f.Current) / float64(f.Total))
			if done != 0 {
				w.Write([]byte(strings.Repeat("=", done-1) + ">"))
			}
			w.Write([]byte(strings.Repeat(" ", width-done)))
		}
		w.Write([]byte("]"))
	}
}

DefaultRenderFunc is the default function used to render the progress bar.

View Source
var GetWinsize func() int

Functions

func Bar added in v1.0.1

func Bar(current, total int64, barWidth int) string

Bar generates a textual progress bar representation based on the current progress.

func DefaultFuncMap added in v1.0.1

func DefaultFuncMap() template.FuncMap

DefaultFuncMap returns the default template function map for progress bar rendering.

func Format added in v1.0.1

func Format(n int64, t string) string

Format formats the given number n according to the specified type t.

func Left added in v1.0.1

func Left(current, total int64, speed float64) time.Duration

Left estimates the remaining time to complete the progress bar based on the current speed.

func Percent added in v1.0.1

func Percent(current, total int64) float64

Percent calculates the completion percentage of the progress bar.

func Speed added in v1.0.1

func Speed(speed float64, t string) string

Speed formats the speed of progress per second, adapting the output based on the specified unit type.

Types

type Frame added in v1.0.1

type Frame struct {
	Unit           string
	BarWidth       int
	Current, Total int64
	Speed          float64
	Additional     string
	Elapsed        time.Duration
}

Frame represents a snapshot of all display-ready fields used to render the progress bar at a given moment. It contains the computed visual components (e.g., completed blocks, percentages, speed, timing information) that are assembled by the renderer into the final output.

type ProgressBar

type ProgressBar[T int | int64] struct {
	// contains filtered or unexported fields
}

ProgressBar represents a customizable progress bar for tracking task progress. It supports configurable templates, units, and refresh intervals.

func New

func New[T int | int64](total T) *ProgressBar[T]

New creates a new ProgressBar with the specified total count and default options. It panics if total is less than or equal to zero.

func (*ProgressBar[T]) Add

func (pb *ProgressBar[T]) Add(n T)

Add adds the specified amount to the progress bar.

func (*ProgressBar[T]) Additional

func (pb *ProgressBar[T]) Additional(s string)

Additional adds the specified string to the progress bar.

func (*ProgressBar[T]) Cancel

func (pb *ProgressBar[T]) Cancel()

Cancel cancels the progress bar.

func (*ProgressBar[T]) Current

func (pb *ProgressBar[T]) Current() int64

Current returns the current count of the progress bar.

func (*ProgressBar[T]) Elapsed

func (pb *ProgressBar[T]) Elapsed() time.Duration

Elapsed returns the elapsed time since the progress bar started. If the progress bar has not started, it returns zero.

func (*ProgressBar[T]) FromReader

func (pb *ProgressBar[T]) FromReader(r io.Reader, w io.Writer) (int64, error)

FromReader starts the progress bar from a reader.

func (*ProgressBar[T]) Message

func (pb *ProgressBar[T]) Message(msg string) error

Message sets a message to be displayed on the progress bar.

func (*ProgressBar[T]) SetRefreshInterval

func (pb *ProgressBar[T]) SetRefreshInterval(interval time.Duration) *ProgressBar[T]

SetRefreshInterval sets progress bar refresh interval time for check speed. If interval is less than or equal to zero, it logs an error message and does not change the interval.

func (*ProgressBar[T]) SetRender added in v1.0.1

func (pb *ProgressBar[T]) SetRender(fn func(w io.Writer, f Frame)) error

SetRender sets progress bar render function.

func (*ProgressBar[T]) SetRenderInterval

func (pb *ProgressBar[T]) SetRenderInterval(interval time.Duration) *ProgressBar[T]

SetRenderInterval sets the interval for updating the progress bar display. If interval is less than or equal to zero, it logs an error message and does not change the interval.

func (*ProgressBar[T]) SetTemplate

func (pb *ProgressBar[T]) SetTemplate(t *template.Template) error

SetTemplate sets progress bar template.

func (*ProgressBar[T]) SetUnit

func (pb *ProgressBar[T]) SetUnit(unit string) *ProgressBar[T]

SetUnit sets progress bar unit.

func (*ProgressBar[T]) SetWidth

func (pb *ProgressBar[T]) SetWidth(barWidth int) *ProgressBar[T]

SetWidth sets the progress bar width. If barWidth is less than or equal to zero, it logs an error message and does not change the width.

func (*ProgressBar[T]) Speed

func (pb *ProgressBar[T]) Speed() float64

Speed returns the current speed of the progress bar.

func (*ProgressBar[T]) Start

func (pb *ProgressBar[T]) Start() error

Start starts the progress bar.

func (*ProgressBar[T]) Total

func (pb *ProgressBar[T]) Total() int64

Total returns the total count of the progress bar.

func (*ProgressBar[T]) Wait

func (pb *ProgressBar[T]) Wait()

Wait blocks until the progress bar is finished.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL