首页 > 其他分享 >Go语言实现多协程文件上传,断点续传--demo

Go语言实现多协程文件上传,断点续传--demo

时间:2024-04-28 17:15:56浏览次数:23  
标签:断点续传 err demo 多协程 current si currentIndex total os

package main

import (
 "fmt"
 "io"
 "os"
 "regexp"
 "strconv"
 "sync"

 "github.com/qianlnk/pgbar"
)

/**
* 需求:
1. 多协程下载文件
2.断点续连
**/
func main() {
 //获取要下载文件
 DownloadFileName := "./123.zip"
 //copy的文件
 copyFileName := "./test.zip"
 storgeFileName := "./current.txt"
 //打开文件
 sfile, err := os.Open(DownloadFileName)
 if err != nil {
  panic(err)
 }
 defer sfile.Close()
 //获取文件大小
 info, _ := sfile.Stat()
 downloadSize := info.Size()
 var scount int64 = 1
 if downloadSize%5 == 0 {
  scount *= 5
 } else {
  scount *= 10
 }
 //分给每个协程的大小
 si := downloadSize / scount
 fmt.Printf("文件总大小:%v, 分片数:%v,每个分片大小:%v\n", downloadSize, scount, si)
 //open copy file
 copyFile, err := os.OpenFile(copyFileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
 if err != nil {
  panic(err)
 }
 storgeFile, err := os.OpenFile(storgeFileName, os.O_CREATE|os.O_RDWR, os.ModePerm)
 if err != nil {
  panic(err)
 }
 defer copyFile.Close()

 var currentIndex int64 = 0
 wg := sync.WaitGroup{}
 fmt.Println("协程进度条")
 pgb := pgbar.New("")
 for ; currentIndex < scount; currentIndex++ {
  wg.Add(1)
  go func(current int64) {
   p := pgb.NewBar(fmt.Sprint((current+1))+"st", int(si))
   // p.SetSpeedSection(900, 100)
   b := make([]byte, 1024)
   bs := make([]byte, 16)
   currentIndex, _ := storgeFile.ReadAt(bs, current*16)
   //取出所有整数
   reg := regexp.MustCompile(`\d+`)
   countStr := reg.FindString(string(bs[:currentIndex]))
   total, _ := strconv.ParseInt(countStr, 10, 0)
   progressBar := 1
   for {
    if total >= si {
     wg.Done()
     break
    }
    //从指定位置开始读
    n, err := sfile.ReadAt(b, current*si+total)
    if err == io.EOF {
     wg.Done()
     break
    }
    //从指定位置开始写
    copyFile.WriteAt(b, current*si+total)
    storgeFile.WriteAt([]byte(strconv.FormatInt(total, 10)+" "), current*16)
    total += int64(n)
    if total >= si/10*int64(progressBar) {
     progressBar += 1
     p.Add(int(si / 10))
    }

   }

  }(currentIndex)
 }
 wg.Wait()
 storgeFile.Close()
 os.Remove(storgeFileName)
 fmt.Println("下载完成")
}

标签:断点续传,err,demo,多协程,current,si,currentIndex,total,os
From: https://www.cnblogs.com/qcy-blog/p/18164061

相关文章

  • WPF所有原生空间使用demo
    //前台窗体<Windowx:Class="WpfTestDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.......
  • 芯科SiWx917学习笔记:1-测试Out of Box Demo
    实验目的:测试OutofBoxDemo实验环境:SimplicityStudioV5实验器材:WirelessStarterKitMainboard(BRD4002ARevA06)+ SiWG917SingleBandWi-FiandBLE8MBFlashRadioBoard(BRD4338ARevA01)实验开始:1.新建工程:在demos中找到OutofBoxDemo(SoC)应用演示工程......
  • Vue3 简单登录管理页面Demo
    目录前言项目基础配置新建项目引入组件项目配置Vue项目配置项目基本结构基础页面布局和路由搭建新增页面,简单跳转LoginViewMainViewrouterApp嵌套路由Test[1-4]Layout.vuerouter给个简单的跳转路由守护,重定向,动态路由,路由传值。这里不做展开描述简单登录页面:烂尾了总结前言这里......
  • 没有对应芯片手册,不知道哪些IO口可以控,测试demo
     //sdk\apps\earphone\include\app_config.h//////////↓↓↓↓↓↓↓↓↓↓codesnippetfromxwh↓↓↓↓↓↓↓↓↓↓////////////////////#defineLED0_IOIO_PORTA_01#defineLED0_ONOFF(x)do{gpio_set_pull_down(LED0_IO,0);\gpio_set......
  • WPF 使用 ManipulationDemo 工具辅助调试设备触摸失效问题
    本文将和大家介绍我所在的团队开源的ManipulationDemo工具。通过ManipulationDemo工具可以提升调试设备触摸失效的效率此工具在GitHub上完全开源,请看https://github.com/dotnet-campus/ManipulationDemo/软件界面效果大概如下可以显示接收到的Win32消息、当前的触摸......
  • 【Java注解】自定义注解的简单demo
    需求场景对于特定字段进行脱敏实现步骤首先创建注解@interface1importjava.lang.annotation.ElementType;2importjava.lang.annotation.Retention;3importjava.lang.annotation.RetentionPolicy;4importjava.lang.annotation.Target;56@Retention(Reten......
  • 微雪 esp32c3 墨水屏显示 demo
    先看esp32c3使用platformio开发墨水屏简介这篇文章,这篇文章中详细说明了从创建项目到烧录代码的整个过程。如果屏幕使用的是H029A01型号能够局部刷新,屏幕驱动关键代码为:GxEPD2_BW<GxEPD2_290,GxEPD2_290::HEIGHT>display(GxEPD2_290(SS,5,2,3));(微雪esp32c3)在使......
  • 泛型模板化设计DEMO
    泛型模板化设计DEMO1.定义Result泛型类packagecom.example.core.mydemo.java.fanxing;publicclassResult<T>{Tresponse;publicTgetResponse(){returnresponse;}publicvoidsetResponse(Tresponse){this.response=res......
  • 小记 Demo
    定义领域模型:AggregateRoot:定义SalesOrder作为聚合根,其中包括订单明细、客户信息、订单总额等。Entity:定义如OrderItem(订单项)、Inventory(库存)等实体。ValueObject:定义如Address(地址)、Money(金额)等值对象。建立仓储接口:使用ABPvNext框架的仓储模式来实现数据的......
  • 接口加密传输设计及AES加解密代码DEMO
    接口加密传输设计及AES加解密代码DEMO接口加密的方案设计:可以将请求的json字符串aes加密,通过params字段传输,接口服务端接收到参数,先解密,然后转换成对象。继续业务逻辑的处理。(另外一种方案是:针对敏感字段aes加密,服务接收端对敏感字段来解密处理)RequestVo对象:privateS......