dongtiao5094 2016-10-14 13:19
浏览 402
已采纳

尝试在Golang中读取gzip文件时出错

I am trying to read gzip files using compress/gzip. I am using http.DetectContentType as I do not know if I get a normal txt file or a gzipped one. My code is very straight forward and as below:

f, err := os.Open(fullpath)
if err != nil {
    log.Panicf("Can not open file %s: %v", fullpath, err)
    return ""
}
defer f.Close()

buff := make([]byte, 512)
_, err = f.Read(buff)
if err != nil && err != io.EOF{
    log.Panicf("Cannot read buffer %v", err);
    return ""
}

switch filetype := http.DetectContentType(buff); filetype {
case "application/x-gzip":
    log.Println("File Type is", filetype)
    reader, err := gzip.NewReader(f)
    if err != nil && err != io.EOF{
        log.Panicf("Cannot read gzip archive %v", err);
        return ""
    }
    defer reader.Close()
    target := "/xx/yy/abcd.txt"
    writer, err := os.Create(target)
    if err != nil {
        log.Panicf("Cannot write unarchived file %v", err);
        return ""
    }
    defer writer.Close()

    _, err = io.Copy(writer, reader)
    return target

The problem is that the gzip reader always errors out saying "Cannot read gzip archive gzip: invalid header" I have tried the zlib library too but in vain. I gzipped the source file in mac using the command line gzip tool. Please show me where I am going wrong.

  • 写回答

1条回答 默认 最新

  • doupiai5597 2016-10-14 13:24
    关注

    You're reading the first 512 bytes of the file, so the gzip.Reader won't ever see that. Since these are regular files, you can seek back to the start after a successful Read:

    f.Seek(0, os.SEEK_SET)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?