go语言实现进度条

Go 复制代码
package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"

	"github.com/vbauerster/mpb/v8"
	"github.com/vbauerster/mpb/v8/decor"
)

type File struct {
	Name string
	Size int
}

func main() {
	rand.Seed(time.Now().UnixNano())

	files := []File{
		{"file-A.txt", 100},
		{"file-B.txt", 80},
		{"file-C.txt", 120},
	}

	var wg sync.WaitGroup
	p := mpb.New(mpb.WithWaitGroup(&wg)) // 初始化进度管理器

	for _, file := range files {
		wg.Add(1)
		go simulateFileRead(p, file, &wg)
	}

	wg.Wait()
	// 给 mpb 终端输出留一帧渲染时间(重要!)
	time.Sleep(100 * time.Millisecond)
	fmt.Println("\n 所有文件读取完成!")
}

func simulateFileRead(p *mpb.Progress, file File, wg *sync.WaitGroup) {
	defer wg.Done()

	bar := p.New(
		int64(file.Size),
		mpb.BarStyle().Lbound("[").Filler("*").Tip(">").Padding(" ").Rbound("]"),
		mpb.PrependDecorators(
			decor.Name(file.Name, decor.WC{W: 12, C: decor.DSyncWidth}),
		),
		mpb.AppendDecorators(
			decor.Percentage(decor.WC{W: 6}),
		),
	)

	chunkSize := 5
	current := 0

	for current < file.Size {
		time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
		toAdd := chunkSize
		if current+chunkSize > file.Size {
			toAdd = file.Size - current
		}
		bar.IncrBy(toAdd)
		current += toAdd
	}
}
相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
胡写代码2 天前
别再前后端各写一套表单校验了
java·后端
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
ttwuai2 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
大勇前进2 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端
yuzhi_liu2 天前
我用 LangGraph4j 实现 Multi-Agent Supervisor
后端
alsmile2 天前
Node-RED 之外,国产规则引擎的新方案:基于标准语法,Go 先行实现
后端·开源·go