Golang USES zlib to compress and uncompress strings
- 2020-06-07 04:37:04
- OfStack
zlib has been used to compress web pages since python. zlib is also used for compression and decompression under golang. The official method of zlib is simple and should be added here.
zlib.NewWriter() can only pass []byte type data. NewWriterLevel can pass compression levels.
package main
import (
"bytes"
"compress/zlib"
"fmt"
"io"
)
func main() {
var in bytes.Buffer
b := []byte(`xiorui.cc`)
w := zlib.NewWriter(&in)
w.Write(b)
w.Close()
var out bytes.Buffer
r, _ := zlib.NewReader(&in)
io.Copy(&out, r)
fmt.Println(out.String())
}
Library package address
import "compress/zlib"
write
func NewWriter
func NewWriter(w io.Writer) *Writer
Read compressed data
func NewReader
func NewReader(r io.Reader) (io.ReadCloser, error)
Set the compression level and compress the data
func NewWriterLevel(w io.Writer, level int) (io.WriteCloser, os.Error)
Here are the levels.
const (
NoCompression = 0
BestSpeed = 1
BestCompression = 9
DefaultCompression = -1
)
const (
NoCompression = flate.NoCompression
BestSpeed = flate.BestSpeed
BestCompression = flate.BestCompression
DefaultCompression = flate.DefaultCompression
)
Write data
func (*Writer) Write
func (z *Writer) Write(p []byte) (n int, err error)
Shut down
func (*Writer) Close
func (z *Writer) Close() error
The efficiency and performance of Golang zlib compression is ok, after all, rsync is also using this compression algorithm. In fact, zlib is one more point than gzip. For example, nginx's gzip compression. I have seen a foreign post before, it is said that zlib is more suitable than gzip for the scene of the balance of speed and compression effect.