从网络上获取zip文件并在Go中解压缩它

huangapple go评论85阅读模式
英文:

Fetch zip file from the web and decompress it in Go

问题

你可以使用Go语言的net/http包来从Web上获取zip压缩文件。你可以使用http.Get函数来发送GET请求并获取响应。然后,你可以使用ioutil.ReadAll函数来读取响应的内容。

获取到zip文件的内容后,你可以将其传递给zip.NewReader函数来创建一个*zip.Reader对象。然后,你可以使用Next方法遍历zip文件中的每个文件,并使用Open方法打开每个文件。

以下是一个示例代码:

package main

import (
	"archive/zip"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func main() {
	// 发送GET请求并获取响应
	resp, err := http.Get("http://example.com/archive.zip")
	if err != nil {
		fmt.Println("Error fetching zip file:", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应的内容
	zipData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading zip file:", err)
		return
	}

	// 创建zip.Reader对象
	zipReader, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
	if err != nil {
		fmt.Println("Error creating zip reader:", err)
		return
	}

	// 遍历zip文件中的每个文件
	for _, file := range zipReader.File {
		// 打开文件
		fileReader, err := file.Open()
		if err != nil {
			fmt.Println("Error opening file:", err)
			continue
		}
		defer fileReader.Close()

		// 读取文件内容
		fileData, err := ioutil.ReadAll(fileReader)
		if err != nil {
			fmt.Println("Error reading file:", err)
			continue
		}

		// 在这里处理文件内容
		fmt.Println("File contents:", string(fileData))
	}
}

请注意,上述代码中的URL是示例URL,你需要将其替换为你要获取的zip文件的实际URL。另外,你还可以根据需要修改代码来处理zip文件中的文件内容。

英文:

How can I fetch a zip archived file from the Web and decompress it in Go? It looks like archive/zip package provides a set of tools to parse the zipped file. However, in order to decompress the zipped file, I have to use zip.OpenReader, which takes the filename as string.

So how can I fetch the zipped file from the Web, and put it into the above function as string...? Or maybe do I have to first fetch the file and put it in one of the directories of my filesystem, and then read it?

答案1

得分: 5

似乎要解压缩zip文件,需要能够随意定位到文件的位置。这意味着,除非你想做一些高级操作,否则它要么是一个本地文件,要么完全在内存中。

假设你已经下载了zip文件,并且将其保存在[]byte中,你可以按照以下方式进行操作:

zipReader := zip.NewReader(bytes.NewReader(zipData), len(zipData))
英文:

It appears that in order to decompress a zip, you need to be able to seek to arbitrary locations. This means that unless you want to do something fancy, it either needs to be a local file or be completely in memory.

Assuming you have downloaded the zip and have it in a []byte, you want to do something like:

zipReader := zip.NewReader(bytes.NewReader(zipData), len(zipData))

huangapple
  • 本文由 发表于 2013年12月4日 08:27:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/20364506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定