如何修复没有头部的 zlib 文件?

huangapple go评论73阅读模式
英文:

How to fix a zlib file without header?

问题

我需要解压一个使用zlib压缩的git对象。尽管该对象使用zlib进行了压缩,但它没有头部(我猜是为了节省带宽)。因此,我试图在对象字节的顶部添加头部,但由于某些原因,zlib仍然抱怨头部无效。我怀疑头部字节是作为字符串文字而不是字节添加的,但我不确定。请参考下面的代码。

package main

import (
	"compress/zlib"
	"fmt"
	"io/ioutil"
	"bytes"
)

func main() {
	b, err := ioutil.ReadFile("raw")
	if err != nil {
		panic(err)
	}
	const header = "\x1f\x8b\x08\x00\x00\x00\x00\x00"
	buf := bytes.NewBuffer(nil)
	if _, err := buf.WriteString(header); err != nil {
		panic(err)
	}
	if _, err := buf.Write(b); err != nil {
		panic(err)
	}
	r, err := zlib.NewReader(buf)
	if err != nil {
		panic(err)
	}
	defer r.Close()
	var db []byte
	if _, err := r.Read(db); err != nil {
		panic(err)
	}
	fmt.Printf("%s", db)
}

错误信息:

panic: zlib: invalid header

goroutine 1 [running]:
main.main()
    /Users/themihai/test/main.go:27 +0x29e
exit status 2
英文:

I need to uncompress a git object which is compressed with zlib. Although the object is compressed with zlib it has no header(to save bandwidth I guess). So I'm trying to add the header on top of the object bytes but for some reasons zlib still complains that the header is not valid. I suspect the header bytes are added as string literal instead of bytes but I'm not sure. See the code below.

package main

import(
        "compress/zlib"
        "io/ioutil"
        "bytes"
        "fmt"
        //      "strings"
)


func main(){
        b, err := ioutil.ReadFile("raw")
        if err !=nil{
                panic(err)
        }
        const header = "\x1f\x8b\x08\x00\x00\x00\x00\x00"
        buf := bytes.NewBuffer(nil)
        if _, err := buf.WriteString(header); err !=nil{
                panic(err)
        }
        if _, err := buf.Write(b); err !=nil{
                panic(err)
        }
        r, err := zlib.NewReader(buf)
        if err !=nil{
                panic(err)
        }
        defer r.Close()
        var db []byte
        if _, err := r.Read(db); err !=nil{
                panic(err)
        }
        fmt.Printf("%s", db)
}

Error

panic: zlib: invalid header

goroutine 1 [running]:
main.main()
    /Users/themihai/test/main.go:27 +0x29e
exit status 2

答案1

得分: 7

这是一个gzip头部,而不是zlib头部。

但是你不需要添加zlib头部。如果是原始的deflate数据,可以使用compress/flate包而不是compress/zlib包。

英文:

That's a gzip header, not a zlib header.

But you don't need to add a zlib header anyway. If it is raw deflate data, then use the compress/flate package instead of compress/zlib.

huangapple
  • 本文由 发表于 2016年2月5日 09:58:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/35215082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定