douhuan2101 2016-04-22 17:41
浏览 60
已采纳

创建要通过Google App Engine投放的tar文件

I'm writing an application for Google AppEngine using Go, and need to tar together a bunch of files to serve to the user when they navigate to a particular URL. At the moment the files are static, and so I could solve this problem by tarring them before upload to the server. In the future I would like to dynamically alter them before tarring, and so would like to learn how to tar & serve the static files on request.

In my init() function I have the following line:

http.HandleFunc("/download.tar", tarit)

The function tarit is the one I am having a problem with, and it currently looks like the following:

func tarit(w http.ResponseWriter, r *http.Request) {
    tarball := tar.NewWriter(w)
    defer tarball.Close()

    info, err := os.Stat("/files")
    if err != nil {
        return
    }

    var baseDir string
    if info.IsDir() {
        baseDir = filepath.Base("/files")
    }

    filepath.Walk("/files", func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        header, err := tar.FileInfoHeader(info, info.Name())
        if err != nil {
            return err
        }

        if baseDir != "" {
            header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, "/files"))
        }

        if err := tarball.WriteHeader(header); err != nil {
            return err
        }

        if info.IsDir() {
            return nil
        }

        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()
        _, err = io.Copy(tarball, file)
        return err
    })
}

The files I am trying to add to the tarball are located in /files, and I've added this folder as a static_dir in the app.yaml.

When navigating to the appropriate URL, the browser downloads a tar file that is only 1 KB in size, and appears to be empty.

I would very much appreciate if someone could point out where I am going wrong, or what I am misunderstanding. I'd also be very happy to provide any other details that you would like.

Thanks!

  • 写回答

1条回答 默认 最新

  • drazvzi741287 2016-04-22 18:06
    关注

    Specify directories using paths relative to the directory containing app.yaml. The path in the posted code is the absolute path "/files". Perhaps you should change it to "files".

    Log the errors returned from os.Stat and filepath.Walk. The errors will probably lead you to the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵