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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器