package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"log"
)
func gUnzipData(data []byte) (resData []byte, err error) {
b := bytes.NewBuffer(data)
var r io.Reader
r, err = gzip.NewReader(b)
if err != nil {
return
}
var resB bytes.Buffer
_, err = resB.ReadFrom(r)
if err != nil {
return
}
resData = resB.Bytes()
return
}
func gZipData(data []byte) (compressedData []byte, err error) {
var b bytes.Buffer
gz := gzip.NewWriter(&b)
_, err = gz.Write(data)
if err != nil {
return
}
if err = gz.Flush(); err != nil {
return
}
if err = gz.Close(); err != nil {
return
}
compressedData = b.Bytes()
return
}
func main() {
// define original data
data := []byte(`MyzYrIyMLyNqwDSTBqSwM2D6KD9sA8S/d3Vyy6ldE+oRVdWyqNQrjTxQ6uG3XBOS0P4GGaIMJEPQ/gYZogwkQ+A0/gSU03fRJvdhIGQ1AMARVdWyqNQrjRFV1bKo1CuNEVXVsqjUK40RVdWyqNQrjRFV1bKo1CuNPmQF870PPsnSNeKI1U/MrOA0/gSU03fRb2A3OsnORNIruhCUYTIrOMTNU7JuGb5RSYJxa6PiMHdiRmFtXLNoY+GVmTD7aOV/K1yo4y0dR7Q=`)
fmt.Println("original data:", data)
fmt.Println("original data len:", len(data))
// compress data
compressedData, compressedDataErr := gZipData(data)
if compressedDataErr != nil {
log.Fatal(compressedDataErr)
}
fmt.Println("compressed data:", compressedData)
fmt.Println("compressed data len:", len(compressedData))
// uncompress data
uncompressedData, uncompressedDataErr := gUnzipData(compressedData)
if uncompressedDataErr != nil {
log.Fatal(uncompressedDataErr)
}
fmt.Println("uncompressed data:", uncompressedData)
fmt.Println("uncompressed data len:", len(uncompressedData))
}
golang: gzip and gunzip --- 2024-04-10
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 坚持早起的第二个月,我遇到了瓶颈期。 起因是清明假期的夜爬华山,打乱了以往的作息。之前晚上九点左右就睡了,早起很容...