在 Go 中写入指定范围的字节到文件
时间:2024-03-21
浏览:324
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《在 Go 中写入指定范围的字节到文件》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我正在使用 go 以 10mb 的并发块下载一个大文件,如下所示。
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
func main() {
chunkSize := 1024 * 1024 * 10 // 10MB
url := "http://path/to/large/zip/file/zipfile.zip"
filepath := "zipfile.zip"
res, _ := http.Head(url)
maps := res.Header
length, _ := strconv.Atoi(maps["Content-Length"][0]) // Get the content length from the header request
// startByte and endByte determines the positions of the chunk that should be downloaded
var startByte = 0
var endByte = chunkSize - 1
for startByte < length {
if endByte > length {
endByte = length - 1
}
go func(startByte, endByte int) {
client := &http.Client {}
req, _ := http.NewRequest("GET", url, nil)
rangeHeader := fmt.Sprintf("bytes=%d-%d", startByte, endByte)
req.Header.Add("Range", rangeHeader)
resp,_ := client.Do(req)
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
addToFile(filepath, startByte, endByte, data)
}(startByte, endByte)
startByte = endByte + 1
endByte += chunkSize
}
}
func addToFile(filepath string, startByte, endByte int, data []byte) {
// TODO: write to byte range in file
}
我应该如何创建文件,并写入文件内与块的字节范围相对应的指定字节范围?
例如,如果我从字节 262144000-272629759 获取数据,则 addtofile 函数应写入 zipfile.zip 中的 262144000-272629759。然后,如果从另一个范围获取数据,则应将其写入 zipfile.zip 中的相应范围。
解决方案
想出了如何做到这一点。如下所示更改 addtofile 函数。
func addToFile(filepath string, startByte int, data []byte) {
f, err := os.OpenFile(filepath, os.O_CREATE | os.O_WRONLY, os.ModeAppend)
if err != nil {
panic("File not found")
}
whence := io.SeekStart
_, err = f.Seek(int64(startByte), whence)
f.Write(data)
f.Sync() //flush to disk
f.Close()
}好了,本文到此结束,带大家了解了《在 Go 中写入指定范围的字节到文件》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
