登录
首页 >  Golang >  Go问答

在Golang中如何压缩符号链接使用archive/zip包?

来源:stackoverflow

时间:2024-03-25 10:00:40 372浏览 收藏

本文讨论如何在 Golang 中使用 "archive/zip" 包压缩包含符号链接的文件夹,同时保留符号链接结构和目标文件。作者尝试使用 "io.copy()" 复制符号链接内容,但发现目标文件内容被复制,导致符号链接丢失。最终,作者使用了一个来自 GitHub pull request 的解决方案,该解决方案将符号链接的目标写入压缩文件中,在 Linux 和 Windows 上进行了测试。

问题内容

我需要以保存结构并将符号链接写入符号链接的方式压缩/解压缩包含符号链接的文件夹。

有没有办法使用 golang 包“archive/zip”来做到这一点?或者任何其他替代方式?

我尝试使用此代码,但“io.copy()”复制了目标文件内容,我们“丢失”了符号链接。

archive, err := os.Create("archive.zip")
if err != nil {
    panic(err)
}
defer archive.Close()
zipWriter := zip.NewWriter(archive)
localPath := "../testdata/sym"
file, err := os.Open(localPath)
defer file.Close()
if err != nil {
    panic(err)
}
w1 , err:= zipWriter.Create("w1")
if _, err = io.Copy(w1, file); err !=nil{
    panic(err)
}
zipWriter.Close()

正确答案


我使用了这个 pr:https://github.com/mholt/archiver/pull/92 并将符号链接的目标写入编写器。

我在 linux 和 windows 上测试了它。

archive, err := os.Create("archive.zip")
if err != nil {
    panic(err)
}
defer archive.Close()
zipWriter := zip.NewWriter(archive)
defer zipWriter.Close()
localPath := "../testdata/sym"
symlinksTarget = "../a/b.in"
file, err := os.Open(localPath)
defer file.Close()
if err != nil {
    panic(err)
}
info, err := os.Lstat(file.Name())
if err != nil {
    panic(err)
}
header, err := zip.FileInfoHeader(info)
if err != nil {
    panic(err)
}
header.Method = zip.Deflate
writer, err := zipWriter.CreateHeader(header)
if err != nil {
    panic(err)
}

// Write symlink's target to writer - file's body for symlinks is the symlink target.
_, err = writer.Write([]byte(filepath.ToSlash(symlinksTarget)))
if err != nil {
    panic(err)
}

以上就是《在Golang中如何压缩符号链接使用archive/zip包?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>