### Start HTTP Server for xbar/SwiftBar (Go) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Starts an HTTP server for progress bar integration with xbar/SwiftBar. This is a snippet to be included in a long-running process. ```go // main.go - Long-running process with HTTP server server := bar.StartHTTPServer("127.0.0.1:19999") // ... keep server running ... ``` -------------------------------- ### Install progressbar Go Package Source: https://github.com/schollz/progressbar/blob/main/README.md Install the latest version of the progressbar package using go get. ```bash go get -u github.com/schollz/progressbar/v3 ``` -------------------------------- ### Default Theme Example Source: https://github.com/schollz/progressbar/blob/main/_autodocs/types.md Illustrates the default theme configuration for a progress bar. ```go ThemeDefault = Theme{ Saucer: "█", SaucerPadding: " ", BarStart: "|", BarEnd: "|", } ``` -------------------------------- ### ASCII Theme Example Source: https://github.com/schollz/progressbar/blob/main/_autodocs/types.md Demonstrates the ASCII theme configuration, using characters like '=' and '>' for the progress bar. ```go ThemeASCII = Theme{ Saucer: "=", SaucerHead: ">", SaucerPadding: ".", BarStart: "[", BarEnd: "]", } ``` -------------------------------- ### Download with Progress Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Use io.Writer interface to download content while displaying progress. This example shows downloading a response body. ```go // Download with progress bar := progressbar.DefaultBytes(resp.ContentLength, "downloading") io.Copy(io.MultiWriter(outFile, bar), resp.Body) ``` -------------------------------- ### Start HTTP Server for Progress Bar State Source: https://github.com/schollz/progressbar/blob/main/_autodocs/INDEX.md Start an HTTP server to expose the progress bar's state. This allows external clients to monitor progress by making HTTP requests. ```go server := bar.StartHTTPServer("127.0.0.1:19999") // curl http://127.0.0.1:19999/state ``` -------------------------------- ### Example: Initialize Reader for File Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Reader.md Demonstrates creating a Reader to wrap a file and update a progress bar during reading. Ensure the file is opened and closed properly, and the progress bar is initialized with the file size. ```go file, _ := os.Open("large_file.bin") defer file.Close() bar := progressbar.DefaultBytes(fileSize, "Reading") reader := progressbar.NewReader(file, bar) io.Copy(io.Discard, reader) // Progress updates automatically ``` -------------------------------- ### StartWithoutRender: Start Timing Without Immediate Render Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Starts the progress bar's internal timing mechanism without rendering it immediately. This allows for delayed rendering, useful when combined with subsequent progress updates. ```go bar.StartWithoutRender() time.Sleep(1 * time.Second) bar.Add(1) // Now renders with timing starting from StartWithoutRender ``` -------------------------------- ### Example: Reading Data with Reader Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Reader.md Shows how to use the Read method of a Reader instance. The progress bar automatically updates as data is read into the buffer. ```go reader := progressbar.NewReader(file, bar) buf := make([]byte, 4096) n, err := reader.Read(buf) // Progress bar advances by n bytes ``` -------------------------------- ### Start HTTP Server Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Launches an HTTP server to expose progress bar state. This server can be used by external UIs to display progress information. ```APIDOC ## StartHTTPServer ### Description Launches an HTTP server to expose progress bar state. This server can be used by external UIs to display progress information. ### Method `StartHTTPServer` ### Parameters #### Path Parameters - **hostPort** (string) - Required - Address and port to bind to, e.g. "0.0.0.0:19999" ### Returns - `*http.Server` instance that can be shut down with `server.Shutdown()` or `server.Close()` ### Example ```go bar := progressbar.Default(1000) server := bar.StartHTTPServer("0.0.0.0:19999") defer server.Close() for i := 0; i < 1000; i++ { bar.Add(1) time.Sleep(1 * time.Millisecond) } ``` ``` -------------------------------- ### StartHTTPServer Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Starts an HTTP server to serve progress bar updates, which can be used for UI elements like OS status bars with xbar extensions. ```APIDOC ## StartHTTPServer ### Description Starts an HTTP server dedicated to serving progress bar updates. Useful for displaying status in UI elements like OS status bars with xbar extensions. ### Method `StartHTTPServer(hostPort string) *http.Server` ### Parameters #### Path Parameters - **hostPort** (string) - Required - Address and port to bind to, e.g. "0.0.0.0:19999". ### Returns - **`*http.Server`** - An `http.Server` instance that can be manually shut down with `server.Shutdown()` or `server.Close()`. ### HTTP Endpoints - `GET /state` - Returns JSON with current State - `GET /desc` - Returns text description of current progress ### Example ```go bar := progressbar.Default(1000) server := bar.StartHTTPServer("0.0.0.0:19999") defer server.Close() go func() { for i := 0; i < 1000; i++ { bar.Add(1) time.Sleep(10 * time.Millisecond) } }() ``` ``` -------------------------------- ### Start HTTP Server for Remote Monitoring Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Starts an HTTP server to expose the progress bar's state remotely. Useful for monitoring progress from other processes or terminals. Ensure the server is closed when done. ```go bar := progressbar.Default(1000, "processing") // Start HTTP server server := bar.StartHTTPServer("127.0.0.1:19999") defer server.Close() // In another process/terminal: // curl http://127.0.0.1:19999/state (JSON) // curl http://127.0.0.1:19999/desc (text) ``` -------------------------------- ### Copy File with Progress Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Use io.Writer interface to copy files while displaying progress. This example shows copying from an input file to an output file. ```go // Copy with progress bar := progressbar.DefaultBytes(fileSize) io.Copy(io.MultiWriter(outFile, bar), inFile) ``` -------------------------------- ### Custom Configuration Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Provides an example of customizing the progress bar's appearance and behavior using various options. ```APIDOC ## Custom Configuration ### Description Configures a progress bar with custom options such as description, width, byte display, and a completion callback. ### Code Example ```go bar := progressbar.NewOptions(1000, progressbar.OptionSetDescription("Processing"), progressbar.OptionSetWidth(20), progressbar.OptionShowBytes(true), progressbar.OptionOnCompletion(func() { fmt.Println("Done!") }), ) ``` ``` -------------------------------- ### Real-Time Dashboard with HTTP Server (Go) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Starts a progress bar with an HTTP server to display its state remotely. Fetch and display the progress status periodically. Ensure the server is closed when done. ```go package main import ( "encoding/json" "fmt" "io" "net/http" "time" "github.com/schollz/progressbar/v3" ) func main() { // Start progress bar with HTTP server bar := progressbar.Default(1000, "Processing") server := bar.StartHTTPServer("127.0.0.1:19999") defer server.Close() // Simulate work go func() { for i := 0; i < 1000; i++ { bar.Add(1) time.Sleep(10 * time.Millisecond) } }() // Fetch and display status every second ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for range ticker.C { resp, err := http.Get("http://127.0.0.1:19999/state") if err != nil { continue } var state progressbar.State json.NewDecoder(resp.Body).Decode(&state) resp.Body.Close() fmt.Printf("Progress: %.0f%% (%d/%d) - ETA: %ds\n", state.CurrentPercent*100, state.CurrentNum, state.Max, int64(state.SecondsLeft)) if state.CurrentNum >= state.Max { break } } } ``` -------------------------------- ### StartProgressBarHTTPServer Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Starts a dedicated HTTP server to serve progress bar updates. This is particularly useful for integrating progress status into UI elements, such as OS status bars with xbar extensions. The server can be manually shut down. ```go func (p *ProgressBar) StartHTTPServer(hostPort string) *http.Server ``` ```go bar := progressbar.Default(1000) server := bar.StartHTTPServer("0.0.0.0:19999") defer server.Close() go func() { for i := 0; i < 1000; i++ { bar.Add(1) time.Sleep(10 * time.Millisecond) } }() ``` -------------------------------- ### Start HTTP Server Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Launches the embedded HTTP server for progress updates. The server can be shut down using its Close() or Shutdown() methods. Ensure the hostPort is correctly formatted. ```go server := progressbar.StartHTTPServer(hostPort string) *http.Server ``` ```go bar := progressbar.Default(1000) server := bar.StartHTTPServer("0.0.0.0:19999") defer server.Close() for i := 0; i < 1000; i++ { bar.Add(1) time.Sleep(1 * time.Millisecond) } ``` -------------------------------- ### Unicode Theme Example Source: https://github.com/schollz/progressbar/blob/main/_autodocs/types.md Presents the Unicode theme, which uses special characters for rendering. Requires Nerd Fonts or Fira Code for proper display. ```go ThemeUnicode = Theme{ Saucer: "", // SaucerHead: "", // SaucerPadding: "", // BarStart: "", // BarStartFilled: "", // BarEnd: "", // BarEndFilled: "", // } ``` -------------------------------- ### Example: Closing Reader Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Reader.md Demonstrates deferring the Close call on a Reader to ensure the progress bar is finalized and the underlying reader is closed, even if errors occur. ```go reader := progressbar.NewReader(file, bar) defer reader.Close() // Auto-finishes progress bar // ... read data ... ``` -------------------------------- ### Always Check Add Errors Source: https://github.com/schollz/progressbar/blob/main/_autodocs/errors.md This example shows the best practice of consistently checking for errors returned by the `Add` method. This is crucial for detecting issues like exceeding the maximum progress value. ```go bar := progressbar.Default(100) for i := 0; i < 1000; i++ { if err := bar.Add(1); err != nil { // Handle error - may indicate max was exceeded log.Fatalf("Progress update failed: %v", err) } } ``` -------------------------------- ### StartWithoutRender Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Starts the progress bar's internal timing mechanism without immediately rendering it. This is useful when you want to begin timing but control the rendering later. ```APIDOC ## StartWithoutRender ### Description Starts the progress bar timing without rendering it immediately. Useful when you want to start timing but render later. ### Method func (p *ProgressBar) StartWithoutRender() ### Example: ```go bar.StartWithoutRender() time.Sleep(1 * time.Second) bar.Add(1) // Now renders with timing starting from StartWithoutRender ``` ``` -------------------------------- ### Process Stream with Progress Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Use io.Writer interface to process a stream with progress. This example shows compressing a file stream while showing progress. ```go // Process stream bar := progressbar.DefaultBytes(1000) compressed := gzip.NewWriter(io.MultiWriter(outFile, bar)) io.Copy(compressed, inFile) ``` -------------------------------- ### CheckProgressBarStarted Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Checks if the progress bar has been initiated, either by the first addition of progress or by rendering. Returns true if started, false otherwise. ```go func (p *ProgressBar) IsStarted() bool ``` ```go if !bar.IsStarted() { bar.RenderBlank() } ``` -------------------------------- ### Initialize ProgressBar with Options Source: https://github.com/schollz/progressbar/blob/main/_autodocs/types.md Demonstrates how to create a ProgressBar instance using a slice of Option functions for customization. This is useful for setting descriptions, width, byte display, and completion callbacks. ```go opts := []progressbar.Option{ progressbar.OptionSetDescription("Processing"), progressbar.OptionSetWidth(20), progressbar.OptionShowBytes(true), progressbar.OptionOnCompletion(func() { fmt.Println("Done!") }), } bar := progressbar.NewOptions(1000, opts...) ``` -------------------------------- ### Show Description at Line End Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Changes the description positioning from the start of the line to the end of the line. The default behavior is to display the description at the line start. ```go bar := progressbar.NewOptions(100, progressbar.OptionShowDescriptionAtLineEnd(), ) // Output: [████ ] Processing ``` -------------------------------- ### Validate Configuration with Defer and Recover Source: https://github.com/schollz/progressbar/blob/main/_autodocs/errors.md This snippet illustrates how to validate configuration at startup using `defer` and `recover` to gracefully handle potential panics caused by invalid settings, such as an invalid spinner type. ```go // Use defer + recover for panic-prone operations deffer func() { if r := recover(); r != nil { log.Fatalf("Invalid configuration: %v", r) } }() bar := progressbar.NewOptions(100, progressbar.OptionSpinnerType(userInputSpinner), ) ``` -------------------------------- ### OptionShowDescriptionAtLineEnd Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Changes the description positioning from the start of the line to the end of the line. ```APIDOC ## OptionShowDescriptionAtLineEnd ### Description Changes the description positioning from the start of the line to the end of the line. ### Method OptionShowDescriptionAtLineEnd ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go bar := progressbar.NewOptions(100, progressbar.OptionShowDescriptionAtLineEnd(), ) // Output: [████ ] Processing ``` ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Default: Create ProgressBar with recommended defaults Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Initializes a ProgressBar with recommended defaults, including width, count display, and performance metrics. It writes output to stderr and is suitable for general-purpose progress tracking. ```go bar := progressbar.Default(100, "downloading") for i := 0; i < 100; i++ { bar.Add(1) } ``` -------------------------------- ### OptionSetElapsedTime Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Enables the display of the elapsed time since the progress bar started. ```APIDOC ## OptionSetElapsedTime ### Description Enables display of elapsed time since progress bar started. ### Parameters #### Query Parameters - **elapsedTime** (bool) - Required - true to show elapsed time. ### Request Example ```go bar := progressbar.NewOptions(100, progressbar.OptionSetElapsedTime(true), ) ``` ``` -------------------------------- ### IsStarted Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Checks if the progress bar has been started, which is indicated by the first addition of progress or a render operation. ```APIDOC ## IsStarted ### Description Returns true if the progress bar has been started (first add or render). ### Method `IsStarted() bool` ### Returns - **bool** - True if the progress bar has started, false otherwise. ### Example ```go if !bar.IsStarted() { bar.RenderBlank() } ``` ``` -------------------------------- ### Reset Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Resets the internal timing clock of the progress bar, clearing the start time and other timing-related state. ```APIDOC ## Reset ### Description Resets the internal timing clock. Clears start time and other timing-related state. ### Method func (p *ProgressBar) Reset() ### Example: ```go bar.Reset() // Reset time calculations ``` ``` -------------------------------- ### Custom Theme Usage Source: https://github.com/schollz/progressbar/blob/main/_autodocs/types.md Shows how to create and apply a custom theme to a progress bar using OptionSetTheme. ```go theme := progressbar.Theme{ Saucer: "▓", SaucerHead: "▒", SaucerPadding: "░", BarStart: "[", BarEnd: "]", } bar := progressbar.NewOptions(100, progressbar.OptionSetTheme(theme), ) ``` -------------------------------- ### GET /desc Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Returns a human-readable text summary of the current progress. This is suitable for simple text-based status displays. ```APIDOC ## GET /desc ### Description Returns a human-readable text summary of the current progress. This is suitable for simple text-based status displays. ### Method GET ### Endpoint /desc ### Parameters #### Query Parameters None ### Request Example ```http GET /desc HTTP/1.1 ``` ### Response #### Success Response (200) - **Content-Type**: text/plain - **Body**: Plain text summary #### Response Format: ``` {CurrentNum}/{Max}, {CurrentPercent}%, {SecondsLeft} left ``` #### Response Examples: For determinate progress: ``` 250/1000, 25.00%, 15m0s left ``` For indeterminate progress (no max): ``` 250/-, 0.00%, 0s left ``` ### Use Case: ```go // Simple text status display resp, _ := http.Get("http://localhost:19999/desc") defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) // "250/1000, 25.00%, 15m0s left" ``` ``` -------------------------------- ### NewOptions64 and NewOptions Constructor Signatures Source: https://github.com/schollz/progressbar/blob/main/_autodocs/errors.md Constructs a new progress bar with specified maximum value and options. Incorrect option values can lead to panics. ```go func NewOptions64(max int64, options ...Option) *ProgressBar func NewOptions(max int, options ...Option) *ProgressBar ``` -------------------------------- ### Create Byte-Based Progress Bar (Known Size) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Optimized for tracking byte throughput when the total file size is known. ```go bar := progressbar.DefaultBytes(fileSize, "downloading") ``` -------------------------------- ### GET /state Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Returns the current progress bar state as JSON. This endpoint is useful for detailed progress tracking in external applications. ```APIDOC ## GET /state ### Description Returns the current progress bar state as JSON. This endpoint is useful for detailed progress tracking in external applications. ### Method GET ### Endpoint /state ### Parameters #### Query Parameters None ### Request Example ```http GET /state HTTP/1.1 ``` ### Response #### Success Response (200) - **Content-Type**: application/json - **Body**: JSON-encoded `State` struct #### Response Fields: - **Max** (int64) - Maximum value (or -1 if indeterminate) - **CurrentNum** (int64) - Current progress count - **CurrentPercent** (float64) - Progress as decimal 0.0-1.0 - **CurrentBytes** (float64) - Total bytes tracked - **SecondsSince** (float64) - Elapsed seconds - **SecondsLeft** (float64) - Estimated seconds remaining - **KBsPerSecond** (float64) - Current throughput in KB/s - **Description** (string) - Current description text #### Response Example ```json { "Max": 1000, "CurrentNum": 250, "CurrentPercent": 0.25, "CurrentBytes": 250, "SecondsSince": 5.0, "SecondsLeft": 15.0, "KBsPerSecond": 50.0, "Description": "downloading" } ``` ### Use Case ```go // Fetch progress from another process resp, _ := http.Get("http://localhost:19999/state") defer resp.Body.Close() var state progressbar.State json.NewDecoder(resp.Body).Decode(&state) fmt.Printf("Progress: %.2f%% (%d/%d)\n", state.CurrentPercent*100, state.CurrentNum, state.Max) ``` ``` -------------------------------- ### Basic Usage Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Demonstrates the basic usage of creating a determinate progress bar and updating its progress. ```APIDOC ## Basic Usage ### Description Creates a determinate progress bar with a known total and updates it incrementally. ### Code Example ```go bar := progressbar.Default(100) for i := 0; i < 100; i++ { bar.Add(1) } ``` ``` -------------------------------- ### Check Progress Bar Status Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Check if the progress bar has been started or if it has completed its progress. Use `IsStarted` and `IsFinished` methods for status checks. ```go bar.IsStarted() // Has bar been started? bar.IsFinished() // Has bar completed? ``` -------------------------------- ### Create Progress Bar with Known Total Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Initialize a progress bar with a known total number of units. Use `Default` for a default configuration, `New` for basic initialization, or `NewOptions` to specify additional options. ```go bar := progressbar.Default(100) // or bar := progressbar.New(100) // or bar := progressbar.NewOptions(100, opts...) ``` -------------------------------- ### xbar/SwiftBar Plugin (Bash) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md A bash script to fetch progress description from a running HTTP server. Handles cases where the server might not be available. ```bash #!/bin/bash # progressbar.60s.sh - xbar plugin # Fetch progress status RESPONSE=$(curl -s http://127.0.0.1:19999/desc 2>/dev/null) if [ -z "$RESPONSE" ]; then echo "No progress" else echo "$RESPONSE" fi ``` -------------------------------- ### Create Byte-Based Progress Bar (Custom Options) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Configures byte-based progress bars with options like showing byte counts and using IEC units (MiB, GiB). ```go bar := progressbar.NewOptions64(5000000, progressbar.OptionShowBytes(true), progressbar.OptionShowTotalBytes(true), progressbar.OptionUseIECUnits(true), // MiB instead of MB ) ``` -------------------------------- ### Default Progress Bar Configuration Source: https://github.com/schollz/progressbar/blob/main/_autodocs/configuration.md Use `Default()` to create a standard progress bar. It includes settings for width, writer, count display, iteration speed, throttle, spinner type, full width, blank state rendering, and completion behavior. ```go Default(max int64, description ...string) *ProgressBar ``` -------------------------------- ### Create New Reader Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Reader.md Instantiates a new Reader, associating an io.Reader with a ProgressBar. This is the entry point for enabling progress tracking on a reader. ```go func NewReader(r io.Reader, bar *ProgressBar) Reader ``` -------------------------------- ### Usage Pattern: Copying with io.Copy Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Reader.md Shows how to use the Reader with the standard `io.Copy` function for efficient data transfer while simultaneously updating a progress bar. This is a common pattern for file-to-file copying. ```go file, _ := os.Open("source.bin") bar := progressbar.DefaultBytes(fileInfo.Size(), "Copying") reader := progressbar.NewReader(file, bar) defer reader.Close() io.Copy(destination, reader) ``` -------------------------------- ### Handle Progress State and Errors Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Checks if the progress bar has started before rendering and handles potential errors during the Add operation. Ensures proper completion and logs fatal errors. ```go bar := progressbar.Default(100) if !bar.IsStarted() { bar.RenderBlank() // Show blank bar } for i := 0; i < 100; i++ { if err := bar.Add(1); err != nil { log.Fatalf("Error: %v", err) } } if bar.IsFinished() { fmt.Println("Progress complete!") } ``` -------------------------------- ### Create Basic Progress Bar Source: https://github.com/schollz/progressbar/blob/main/_autodocs/INDEX.md Use `progressbar.Default` to create a simple progress bar with a specified maximum value. This is suitable for basic progress tracking. ```go bar := progressbar.Default(100) for i := 0; i < 100; i++ { bar.Add(1) } ``` -------------------------------- ### Example of Panic from Invalid Spinner Type Source: https://github.com/schollz/progressbar/blob/main/_autodocs/errors.md Illustrates how providing an invalid spinner type to NewOptions can cause a panic. Ensure spinner types are within the valid range (0-75). ```go // This will panic bar := progressbar.NewOptions(100, progressbar.OptionSpinnerType(99), // Panic: invalid spinner type ) ``` -------------------------------- ### OptionShowBytes Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Configures the progress bar to display throughput in KB/s or MB/s. This option updates the progress bar to show the byte rate. ```APIDOC ## OptionShowBytes ### Description Displays throughput in KB/s or MB/s. Updates the progress bar configuration to show byte rate. ### Parameters #### Query Parameters - **val** (bool) - Required - true to show byte throughput. ### Request Example ```go bar := progressbar.NewOptions(1000000, progressbar.OptionShowBytes(true), ) ``` ``` -------------------------------- ### Reset: Reset Progress Bar Timing Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Resets the internal timing clock of the progress bar, clearing the start time and other timing-related state. Use to recalculate elapsed time from the current point. ```go bar.Reset() // Reset time calculations ``` -------------------------------- ### Create Progress Bar for Bytes Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Initialize a progress bar specifically for tracking byte progress. Provide the total number of bytes to be processed. ```go bar := progressbar.DefaultBytes(5000000) // 5MB ``` -------------------------------- ### Handle Detail Row Errors Gracefully Source: https://github.com/schollz/progressbar/blob/main/_autodocs/errors.md This example demonstrates how to handle errors when adding detail rows to a progress bar. It covers cases where the bar might not be configured for details or has already finished. ```go bar := progressbar.NewOptions(100, progressbar.OptionSetMaxDetailRow(3), ) if err := bar.AddDetail(statusMsg); err != nil { // Bar not configured for details or already finished log.Printf("Cannot add detail: %v", err) // Fallback to other logging mechanism } ``` -------------------------------- ### GET /desc Endpoint Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Fetches a human-readable text summary of the current progress. This endpoint is suitable for simple status displays. The format includes current count, percentage, and estimated time left. ```http GET /desc HTTP/1.1 ``` ```text 250/1000, 25.00%, 15m0s left ``` ```text 250/-, 0.00%, 0s left ``` ```go // Simple text status display resp, _ := http.Get("http://localhost:19999/desc") defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) // "250/1000, 25.00%, 15m0s left" ``` -------------------------------- ### Default Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Creates a progress bar with recommended defaults, including width, count, iterations/sec, stderr output, throttling, and fullWidth enabled. Supports an optional description prefix. ```APIDOC ## Default ### Description Creates a progress bar with recommended defaults: width=10, shows count and iterations/sec, writes to stderr, with throttling and fullWidth enabled. ### Signature ```go func Default(max int64, description ...string) *ProgressBar ``` ### Parameters #### Path Parameters - **max** (int64) - Required - Maximum value. Use -1 for spinner mode. - **description** (...string) - Optional - Optional description prefix to display. ### Returns - ** *ProgressBar** - Pointer to configured ProgressBar. ### Example ```go bar := progressbar.Default(100, "downloading") for i := 0; i < 100; i++ { bar.Add(1) } ``` ``` -------------------------------- ### Selecting Progress Bar Themes Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Utilities.md Choose a progress bar theme based on terminal capabilities, such as Unicode or ASCII support. Use OptionSetTheme to apply the selected theme during progress bar initialization. ```go var theme progressbar.Theme if supportsUnicode() { theme = progressbar.ThemeUnicode } else { theme = progressbar.ThemeASCII // Fallback for ASCII terminals } bar := progressbar.NewOptions(100, progressbar.OptionSetTheme(theme), ) ``` -------------------------------- ### Download with Bytes Display Source: https://github.com/schollz/progressbar/blob/main/_autodocs/configuration.md Configures a progress bar to show download progress with both current and total bytes displayed. Useful for tracking file transfers. ```go bar := progressbar.NewOptions64(fileSize, progressbar.OptionSetDescription("Downloading"), progressbar.OptionShowBytes(true), progressbar.OptionShowTotalBytes(true), progressbar.OptionSetWriter(os.Stderr), progressbar.OptionFullWidth(), ) ``` -------------------------------- ### GET /state Endpoint Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Retrieves the current progress bar state as a JSON object. This is useful for detailed progress tracking in external applications. The response includes Max, CurrentNum, CurrentPercent, and estimated time remaining. ```http GET /state HTTP/1.1 ``` ```json { "Max": 1000, "CurrentNum": 250, "CurrentPercent": 0.25, "CurrentBytes": 250, "SecondsSince": 5.0, "SecondsLeft": 15.0, "KBsPerSecond": 50.0, "Description": "downloading" } ``` ```go // Fetch progress from another process resp, _ := http.Get("http://localhost:19999/state") defer resp.Body.Close() var state progressbar.State json.NewDecoder(resp.Body).Decode(&state) fmt.Printf("Progress: %.2f%% (%d/%d)\n", state.CurrentPercent*100, state.CurrentNum, state.Max) ``` -------------------------------- ### New64: Create ProgressBar with int64 max and default options Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Use this function to quickly create a ProgressBar with a specified int64 maximum value using the default configuration. It's ideal for simple progress tracking where custom options are not needed. ```go bar := progressbar.New64(5000) ``` -------------------------------- ### Progress Bar Constructors (Go) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/00-START-HERE.md Available functions for creating new ProgressBar instances with different configurations. Supports integer and int64 maximum values, custom options, and byte-based progress. ```go New(max int) *ProgressBar New64(max int64) *ProgressBar NewOptions(max int, opts ...Option) *ProgressBar Default(max int64, desc ...string) *ProgressBar DefaultBytes(maxBytes int64, desc ...string) *ProgressBar DefaultSilent(max int64, desc ...string) *ProgressBar NewReader(r io.Reader, bar *ProgressBar) Reader ``` -------------------------------- ### Process Multiple Files with Progress Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Iterate over a collection of files, processing each one and updating a progress bar. Initialize the progress bar with the total number of files to process. ```go bar := progressbar.Default(int64(len(files))) for _, file := range files { processFile(file) bar.Add(1) } ``` -------------------------------- ### Common Progress Bar Methods (Go) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/00-START-HERE.md Essential methods for interacting with a ProgressBar instance. Allows incrementing, setting specific values, finishing, changing the description, and querying the bar's state. ```go bar.Add(1) // Increment progress bar.Set(50) // Jump to position 50 bar.Finish() // Complete the bar bar.Describe("text") // Change description bar.State() // Get current metrics bar.IsFinished() // Check completion ``` -------------------------------- ### OptionShowTotalBytes Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Configures the progress bar to display the total bytes in the count. This allows for a "current/total" display of bytes. ```APIDOC ## OptionShowTotalBytes ### Description Displays the total bytes in the count (e.g., "23/100" vs. "23"). ### Parameters #### Query Parameters - **flag** (bool) - Required - true to show total in count display. ### Request Example ```go bar := progressbar.NewOptions(1000, progressbar.OptionShowTotalBytes(false), // Show only current ) ``` ``` -------------------------------- ### DefaultBytes Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Creates a progress bar optimized for byte throughput with recommended defaults, including showing bytes/sec and count, fullWidth, and writing to stderr. Supports an optional description prefix. ```APIDOC ## DefaultBytes ### Description Creates a progress bar optimized for byte throughput with recommended defaults: shows bytes/sec and count, fullWidth, writes to stderr. ### Signature ```go func DefaultBytes(maxBytes int64, description ...string) *ProgressBar ``` ### Parameters #### Path Parameters - **maxBytes** (int64) - Required - Maximum bytes to track. Use -1 for spinner. - **description** (...string) - Optional - Optional description prefix. ### Returns - ** *ProgressBar** - Pointer to configured ProgressBar. ### Example ```go bar := progressbar.DefaultBytes(1000000, "downloading") bar.Add64(5000) ``` ``` -------------------------------- ### Create Byte-Based Progress Bar (Unknown Size) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Tracks byte throughput for operations where the total size is unknown, using a spinner animation. ```go bar := progressbar.DefaultBytes(-1, "uploading") ``` -------------------------------- ### OptionShowIts Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Configures the progress bar to display iterations per second. The unit label defaults to "it" and can be displayed in "it/s", "it/min", or "it/hr". ```APIDOC ## OptionShowIts ### Description Displays iterations per second. The unit label defaults to "it" and displays as "it/s", "it/min", or "it/hr" depending on rate. ### Request Example ```go bar := progressbar.NewOptions(100, progressbar.OptionShowIts(), ) ``` ``` -------------------------------- ### Basic Progress Bar Usage Source: https://github.com/schollz/progressbar/blob/main/README.md Demonstrates a simple progress bar that increments from 0 to 100. Requires a time.Sleep for visual effect. ```golang bar := progressbar.Default(100) for i := 0; i < 100; i++ { bar.Add(1) time.Sleep(40 * time.Millisecond) } ``` -------------------------------- ### NewOptions: Create ProgressBar with int max and custom options Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md This is a convenience wrapper around NewOptions64 for creating a ProgressBar with an int maximum value and custom options. Use it when your maximum value fits within an int and you need to apply specific configurations. ```go bar := progressbar.NewOptions(1000, progressbar.OptionSetDescription("Uploading"), ) ``` -------------------------------- ### Creating Multiple Progress Bars Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Instantiate separate progress bars for different operations. Use OptionSetDescription to label each bar. ```go bar1 := progressbar.NewOptions(100, progressbar.OptionSetDescription("Step 1: "), ) bar2 := progressbar.NewOptions(100, progressbar.OptionSetDescription("Step 2: "), ) for i := 0; i < 100; i++ { bar1.Add(1) } bar1.Finish() for i := 0; i < 100; i++ { bar2.Add(1) } bar2.Finish() ``` -------------------------------- ### Create Determinate Progress Bar (Large Counts) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Handles very large counts using int64 for progress tracking. ```go bar := progressbar.New64(1000000000) // 1 billion items ``` -------------------------------- ### Configure Progressbar Metrics Display Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Enable and configure various metrics to be displayed with the progress bar, such as current/total count, iterations per second, bytes per second, elapsed time, and predicted time remaining. ```go bar := progressbar.NewOptions(1000, // Show current/total count progressbar.OptionShowCount(), // (500/1000) // Show iterations per second progressbar.OptionShowIts(), // 100 it/s // Show bytes per second progressbar.OptionShowBytes(true), // 5.2 MB/s // Show elapsed time progressbar.OptionSetElapsedTime(true), // [1m23s] // Show predicted time remaining progressbar.OptionSetPredictTime(true), // [1m23s:2m34s] // Keep elapsed time after finish progressbar.OptionShowElapsedTimeOnFinish(), ) ``` -------------------------------- ### Create, Update, and Finish Progress Bar (Go) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/00-START-HERE.md Basic usage for creating a default progress bar, incrementing its value, and finishing it. Ensure the 'progressbar/v3' package is imported. ```go import "github.com/schollz/progressbar/v3" // Create bar := progressbar.Default(100) // Update bar.Add(1) // Finish bar.Finish() ``` -------------------------------- ### NewOptions64: Create ProgressBar with int64 max and custom options Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Use this function to create a ProgressBar with a specific int64 maximum value and apply custom configurations using Option functions. It's suitable for scenarios requiring fine-grained control over the progress bar's appearance and behavior. ```go bar := progressbar.NewOptions64(100, progressbar.OptionSetDescription("Processing"), progressbar.OptionShowBytes(true), progressbar.OptionSetWidth(20), ) bar.Add64(50) ``` -------------------------------- ### Create Determinate Progress Bar (Custom Options) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Allows customization of progress bar appearance and behavior, such as setting a description and showing the count. ```go bar := progressbar.NewOptions(500, progressbar.OptionSetDescription("Processing"), progressbar.OptionShowCount(), ) ``` -------------------------------- ### Constructor Functions Source: https://github.com/schollz/progressbar/blob/main/_autodocs/MANIFEST.md Functions to create new ProgressBar instances with various configurations. ```APIDOC ## Constructor Functions ### New Creates a new ProgressBar with a specified maximum value. - **Signature**: `New(max int) *ProgressBar` ### New64 Creates a new ProgressBar with a specified maximum value (int64). - **Signature**: `New64(max int64) *ProgressBar` ### NewOptions Creates a new ProgressBar with a specified maximum value and custom options. - **Signature**: `NewOptions(max int, options ...Option) *ProgressBar` ### NewOptions64 Creates a new ProgressBar with a specified maximum value (int64) and custom options. - **Signature**: `NewOptions64(max int64, options ...Option) *ProgressBar` ### Default Creates a default ProgressBar with a specified maximum value and an optional description. - **Signature**: `Default(max int64, description ...string) *ProgressBar` ### DefaultSilent Creates a default ProgressBar that does not render output, with a specified maximum value and an optional description. - **Signature**: `DefaultSilent(max int64, description ...string) *ProgressBar` ### DefaultBytes Creates a default ProgressBar for byte counts, with a specified maximum value and an optional description. - **Signature**: `DefaultBytes(maxBytes int64, description ...string) *ProgressBar` ### DefaultBytesSilent Creates a default ProgressBar for byte counts that does not render output, with a specified maximum value and an optional description. - **Signature**: `DefaultBytesSilent(maxBytes int64, description ...string) *ProgressBar` ### NewReader Wraps an `io.Reader` with a ProgressBar to track read progress. - **Signature**: `NewReader(r io.Reader, bar *ProgressBar) Reader` ``` -------------------------------- ### New: Create ProgressBar with int max and default options Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md This function creates a ProgressBar with a specified int maximum value using default options. It's a straightforward way to initialize a progress bar for common use cases. ```go bar := progressbar.New(100) ``` -------------------------------- ### Custom Progress Bar Configuration Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Configure progress bars with custom options such as description, width, byte display, and completion callbacks. This allows for tailored progress reporting. ```go bar := progressbar.NewOptions(1000, progressbar.OptionSetDescription("Processing"), progressbar.OptionSetWidth(20), progressbar.OptionShowBytes(true), progressbar.OptionOnCompletion(func() { fmt.Println("Done!") }), ) ``` -------------------------------- ### Download Progress Tracking Source: https://github.com/schollz/progressbar/blob/main/_autodocs/README.md Track download progress by initializing the bar with the content length and piping the response body through it. This is useful for monitoring large file downloads. ```go resp, _ := http.DefaultClient.Get(url) defer resp.Body.Close() bar := progressbar.DefaultBytes(resp.ContentLength, "downloading") io.Copy(io.MultiWriter(file, bar), resp.Body) ``` -------------------------------- ### DefaultBytes() Source: https://github.com/schollz/progressbar/blob/main/_autodocs/configuration.md Creates a default progress bar optimized for byte-based progress. It takes a maximum byte count and an optional description, configuring the bar to display byte counts and total bytes. ```APIDOC ## DefaultBytes() ### Description Creates a default progress bar optimized for byte-based progress. It takes a maximum byte count and an optional description, configuring the bar to display byte counts and total bytes. ### Method Signature ```go DefaultBytes(maxBytes int64, description ...string) *ProgressBar ``` ### Default Settings | Setting | Value | |---------|-------| | Width | 10 | | Writer | os.Stderr | | Show Bytes | Yes | | Show Total Bytes | Yes | | Show Count | Yes | | Throttle | 65ms | | Spinner Type | 14 | | Full Width | Yes | | Render Blank State | Yes | | On Completion | Print newline to stderr | ``` -------------------------------- ### Wrap Reader for Progress Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Wrap an os.File with progressbar.NewReader to track reading progress. Ensure to close both the file and the reader. ```go // Wrap a reader to track progress file, _ := os.Open("input.bin") defer file.Close() bar := progressbar.DefaultBytes(fileSize, "reading") reader := progressbar.NewReader(file, bar) defer reader.Close() io.Copy(destination, reader) ``` -------------------------------- ### Show Bytes Throughput (KB/s, MB/s) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Use this option to display throughput in human-readable byte formats like KB/s or MB/s. Set the boolean parameter to true to enable this display. ```go bar := progressbar.NewOptions(1000000, progressbar.OptionShowBytes(true), ) ``` -------------------------------- ### Track Download Progress Source: https://github.com/schollz/progressbar/blob/main/_autodocs/INDEX.md Integrate progress bar with `io.Copy` to track download progress. The progress bar can be configured to display bytes downloaded. ```go resp, _ := http.DefaultClient.Get(url) bar := progressbar.DefaultBytes(resp.ContentLength, "downloading") io.Copy(io.MultiWriter(file, bar), resp.Body) ``` -------------------------------- ### OptionSetDescription Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md Sets the description text displayed with the progress bar. This text can be updated dynamically. ```APIDOC ## OptionSetDescription ### Description Sets the description text displayed with the progress bar. This text can be updated dynamically. ### Method OptionSetDescription ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **description** (string) - Required - Text to display before or after the bar. Default is "". ### Request Example ```go bar := progressbar.NewOptions(100, progressbar.OptionSetDescription("Processing: "), ) ``` ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Configure Progressbar Spinners Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Select and configure different spinner types for the progress bar, including predefined options like pipes, fish, and dots, or define a custom sequence of characters. ```go // Pipes spinner (default) bar := progressbar.NewOptions64(-1, progressbar.OptionSpinnerType(9), // |, /, -, \ ) // Fish spinner bar := progressbar.NewOptions64(-1, progressbar.OptionSpinnerType(12), // >))'> ) // Dots spinner bar := progressbar.NewOptions64(-1, progressbar.OptionSpinnerType(8), // . o O @ * ) // Custom spinner bar := progressbar.NewOptions64(-1, progressbar.OptionSpinnerCustom([]string{"◜", "◝", "◞", "◟"}), ) ``` -------------------------------- ### Use IEC Units for Byte Display Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/Options.md OptionUseIECUnits enables the display of byte sizes using IEC binary units (KiB, MiB, GiB) instead of standard SI units (kB, MB, GB). This is useful for representing file sizes or memory usage accurately in a binary context. Ensure OptionShowBytes is also enabled to display byte counts. ```go bar := progressbar.NewOptions(1000000000, progressbar.OptionShowBytes(true), progressbar.OptionUseIECUnits(true), // Shows MiB instead of MB ) ``` -------------------------------- ### Default Bytes Progress Bar Configuration Source: https://github.com/schollz/progressbar/blob/main/_autodocs/configuration.md Use `DefaultBytes()` to create a progress bar specifically for byte operations. It includes settings for width, writer, byte display, total byte display, count display, throttle, spinner type, full width, blank state rendering, and completion behavior. ```go DefaultBytes(maxBytes int64, description ...string) *ProgressBar ``` -------------------------------- ### Configure Progressbar Colors Source: https://github.com/schollz/progressbar/blob/main/_autodocs/usage-guide.md Enable color codes for the progress bar and customize the description text color and spinner color using predefined color codes. ```go bar := progressbar.NewOptions(100, progressbar.OptionEnableColorCodes(true), progressbar.OptionSetDescription("[cyan]Processing[reset] "), // Customize spinner color progressbar.OptionSetSpinnerColorCode("green"), ) ``` -------------------------------- ### New Source: https://github.com/schollz/progressbar/blob/main/_autodocs/api-reference/ProgressBar.md Returns a new ProgressBar with the specified int maximum using default options. ```APIDOC ## New ### Description Returns a new ProgressBar with the specified int maximum using default options. ### Signature ```go func New(max int) *ProgressBar ``` ### Parameters #### Path Parameters - **max** (int) - Required - Maximum value for the progress bar. ### Returns - ** *ProgressBar** - Pointer to newly initialized ProgressBar. ### Example ```go bar := progressbar.New(100) ``` ``` -------------------------------- ### Default() Source: https://github.com/schollz/progressbar/blob/main/_autodocs/configuration.md Creates a default progress bar with a specified maximum value and an optional description. It uses a default width, writer, and spinner type, along with other predefined settings for displaying progress. ```APIDOC ## Default() ### Description Creates a default progress bar with a specified maximum value and an optional description. It uses a default width, writer, and spinner type, along with other predefined settings for displaying progress. ### Method Signature ```go Default(max int64, description ...string) *ProgressBar ``` ### Default Settings | Setting | Value | |---------|-------| | Width | 10 | | Writer | os.Stderr | | Show Count | Yes | | Show Iterations/Sec | Yes | | Throttle | 65ms | | Spinner Type | 14 | | Full Width | Yes | | Render Blank State | Yes | | On Completion | Print newline to stderr | ``` -------------------------------- ### Multi-Process Progress Monitoring (Go) Source: https://github.com/schollz/progressbar/blob/main/_autodocs/endpoints.md Monitors the progress of a remote process by querying its state via HTTP. Reports if the process is not running. ```go // monitor.go package main import ( "fmt" "net/http" ) func monitorProgress(hostPort string) { resp, err := http.Get(fmt.Sprintf("http://%s/state", hostPort)) if err != nil { fmt.Println("Process not running") return } defer resp.Body.Close() var state progressbar.State json.NewDecoder(resp.Body).Decode(&state) fmt.Printf("Status: %d/%d (%.1f%%)\n", state.CurrentNum, state.Max, state.CurrentPercent*100) } ```