在 Go 中内存内 gzip 压缩

在 Go 中,你可以使用内置的 gzip 库和 bytes.Buffer 来压缩 []byte,获得包含 gzip 压缩数据的 []byte

go_gzip_inmemory_snippet.go
content := "Hello World!"
buf := &bytes.Buffer{}
gzWriter := gzip.NewWriter(buf)
gzWriter.Write([]byte(content))
gzWriter.Close()

此完整示例在内存中压缩数据,然后将其写入名为 text.txt.gz 的文件。注意你也可以直接 gzip 到文件中,如果你不需要对压缩数据做其他事情,你也可以查看我们的上一篇文章如何在 Go 中写入 gzip 文件

go_gzip_inmemory_main.go
package main

import (
    "compress/gzip"
    "os"
)

func main() {
    content := "Hello World!"
    // 初始化 gzip
    buf := &bytes.Buffer{}
    gzWriter := gzip.NewWriter(buf)
    gzWriter.Write([]byte(content))
    gzWriter.Close()
    // 将缓冲区转换为
    ioutil.WriteFile("test.txt.gz", buf.Bytes(), 0644)
}

你可以使用 zcat test.txt.gz 来查看内容已正确写入文件。


Check out similar posts by category: Go