drip5880 2019-08-19 15:02
浏览 56
已采纳

如何在Go中实现PHP gzopen?

I have to convert a PHP script into Go and am now stumped with a problem (I forsee many more to come).

In the script, it uses gzopen to open both .gz and non .gz files and then takes the read data and returns a MD5-hash version of it. I have tried using zlib.NewReader, gzip.NewReader and even flate but they are not working. Can someone point me in the right direction?

file, err := os.Open("somefile.dat")
if err != nil {
  return err
}

// rc := flate.NewReader(f) //error: corrupt input before offset 5
// rc, err := zlib.NewReader(f) //error: invalid header
// rc, err := gzip.NewReader(f) //error: invalid header
if err != nil {
  return err
}

buffer := make([]byte, 4096)
rc.Read(buffer)

Note: With regards to converting to MD5 hash, i followed the example here I originally used the md5.Sum() but that returned a [Size]byte where Size is 16bytes which was not what i needed. I had to convert the MD5 checksum into a 32 character hexadecimal string for it to match the checksum i needed. Hope this helps anybody else.

  • 写回答

1条回答 默认 最新

  • dtvhqlc57127 2019-08-19 15:29
    关注

    Since you need to support reading from both gzip and non-gzip files, add a check to see if the if gzip.NewReader returns the ErrHeader error. If that is returned, fallback to reading the file normally:

    file, err := os.Open("somefile.dat")
    if err != nil {
        return err
    }
    
    var rc io.ReadCloser
    if gz, err := gzip.NewReader(file); err == gzip.ErrHeader {
        if _, err := file.Seek(0, io.SeekStart); err != nil {
            return err
        }
        rc = file
    } else if err == nil {
        rc = gz
    } else {
        return err
    }
    
    md5sum := md5.New()
    if _, err := io.Copy(md5sum, rc); err != nil {
        return err
    }
    
    if err := rc.Close(); err != nil {
        return err
    }
    
    // TODO: md5sum.Sum
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像