golang zlib压缩解压缩
package main
import (
"bytes"
"compress/zlib"
"fmt"
"io"
"os"
)
//进行zlib压缩
func DoZlibCompress(src []byte) []byte {
var in bytes.Buffer
w := zlib.NewWriter(&in)
w.Write(src)
w.Close()
return in.Bytes()
}
//进行zlib解压缩
func DoZlibUnCompress(compressSrc []byte) []byte {
b := bytes.NewReader(compressSrc)
var out bytes.Buffer
r, _ := zlib.NewReader(b)
io.Copy(&out, r)
return out.Bytes()
}
func main() {
buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207,
47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147}
b := bytes.NewReader(buff)
r, err := zlib.NewReader(b)
if err != nil {
panic(err)
}
io.Copy(os.Stdout, r)
r.Close()
zip := DoZlibCompress([]byte("hello, world
"))
fmt.Println(zip)
fmt.Println(string(DoZlibUnCompress(zip)))
}
golang gzip压缩解压缩
package main
import (
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"io/ioutil"
)
func main() {
var b bytes.Buffer
gz := gzip.NewWriter(&b)
if _, err := gz.Write([]byte("hello")); err != nil {
panic(err)
}
if err := gz.Flush(); err != nil {
panic(err)
}
if err := gz.Close(); err != nil {
panic(err)
}
str := base64.StdEncoding.EncodeToString(b.Bytes())
fmt.Println("base64 encode: ",str)
data, _ := base64.StdEncoding.DecodeString(str)
fmt.Println("base64 decode:",data)
rdata := bytes.NewReader(data)
r, _ := gzip.NewReader(rdata)
s, _ := ioutil.ReadAll(r)
fmt.Println("源字符串:",string(s))
}
输出:
base64 encode: H4sIAAAAAAAA/8pIzcnJBwAAAP//AQAA//+GphA2BQAAAA==
base64 decode: [31 139 8 0 0 0 0 0 0 255 202 72 205 201 201 7 0 0 0 255 255 1 0 0 255 255 134 166 16 54 5 0 0 0]
源字符串: hello