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 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1