Golang进度条库推荐与使用指南

Golang进度条库推荐与使用指南 大家好,

这是我的进度条库:

GitHub GitHub

ermanimer/progress_bar

ermanimer/progress_bar

Go 进度条。通过在 GitHub 上创建账户来为 ermanimer/progress_bar 的开发做出贡献。

请看一看,我从你们的评论中学到了很多。


更多关于Golang进度条库推荐与使用指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang进度条库推荐与使用指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这是一个很不错的进度条库,设计简洁且易于使用。我来分析一下它的核心功能并给出使用示例。

核心特性分析

你的 progress_bar 库主要提供了:

  1. 可定制的进度条显示
  2. 支持并发安全操作
  3. 灵活的进度更新方式

基本使用示例

package main

import (
    "time"
    pb "github.com/ermanimer/progress_bar"
)

func main() {
    // 创建进度条,总任务数为100
    bar := pb.New(100)
    
    // 开始显示进度条
    bar.Start()
    
    // 模拟任务执行
    for i := 0; i < 100; i++ {
        time.Sleep(50 * time.Millisecond)
        bar.Increment() // 每次增加1
    }
    
    // 完成并清理显示
    bar.Finish()
}

高级功能示例

func advancedExample() {
    // 自定义配置
    bar := pb.NewWithConfig(pb.Config{
        Total:     200,
        BarLength: 50,
        ShowSpeed: true,
        ShowTime:  true,
    })
    
    bar.Start()
    
    // 批量更新进度
    bar.Add(50) // 直接增加50
    
    // 设置具体进度值
    bar.Set(75) // 设置到75%
    
    // 并发安全的进度更新
    go func() {
        for i := 0; i < 50; i++ {
            time.Sleep(30 * time.Millisecond)
            bar.Increment()
        }
    }()
    
    go func() {
        for i := 0; i < 50; i++ {
            time.Sleep(20 * time.Millisecond)
            bar.Increment()
        }
    }()
    
    time.Sleep(3 * time.Second)
    bar.Finish()
}

自定义模板示例

func customTemplateExample() {
    bar := pb.New(100)
    
    // 使用自定义显示模板
    bar.SetTemplate(`{{.Bar}} {{.Percent}}% ({{.Current}}/{{.Total}})`)
    
    bar.Start()
    
    for i := 0; i < 100; i++ {
        time.Sleep(100 * time.Millisecond)
        bar.Increment()
    }
    
    bar.Finish()
}

实际应用场景

func downloadExample() {
    // 模拟文件下载
    fileSize := int64(1024 * 1024 * 100) // 100MB
    bar := pb.New64(fileSize)
    bar.SetUnits(pb.U_BYTES)
    
    bar.Start()
    
    // 模拟下载过程
    downloaded := int64(0)
    chunkSize := int64(1024 * 512) // 512KB
    
    for downloaded < fileSize {
        time.Sleep(100 * time.Millisecond)
        downloaded += chunkSize
        if downloaded > fileSize {
            downloaded = fileSize
        }
        bar.Set64(downloaded)
    }
    
    bar.Finish()
}

这个库的API设计很直观,对于需要显示进度反馈的CLI应用来说非常实用。并发安全的特性让它在多goroutine场景下也能稳定工作。

回到顶部