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

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

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方法打开每个文件。

以下是一个示例代码:

  1. package main
  2. import (
  3. "archive/zip"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. )
  9. func main() {
  10. // 发送GET请求并获取响应
  11. resp, err := http.Get("http://example.com/archive.zip")
  12. if err != nil {
  13. fmt.Println("Error fetching zip file:", err)
  14. return
  15. }
  16. defer resp.Body.Close()
  17. // 读取响应的内容
  18. zipData, err := ioutil.ReadAll(resp.Body)
  19. if err != nil {
  20. fmt.Println("Error reading zip file:", err)
  21. return
  22. }
  23. // 创建zip.Reader对象
  24. zipReader, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
  25. if err != nil {
  26. fmt.Println("Error creating zip reader:", err)
  27. return
  28. }
  29. // 遍历zip文件中的每个文件
  30. for _, file := range zipReader.File {
  31. // 打开文件
  32. fileReader, err := file.Open()
  33. if err != nil {
  34. fmt.Println("Error opening file:", err)
  35. continue
  36. }
  37. defer fileReader.Close()
  38. // 读取文件内容
  39. fileData, err := ioutil.ReadAll(fileReader)
  40. if err != nil {
  41. fmt.Println("Error reading file:", err)
  42. continue
  43. }
  44. // 在这里处理文件内容
  45. fmt.Println("File contents:", string(fileData))
  46. }
  47. }

请注意,上述代码中的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中,你可以按照以下方式进行操作:

  1. 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:

  1. 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:

确定