Golang uses zlib to compress and decompress strings

Time:2020-4-4

In Python, zlib is used to compress web pages. Zlib is also used for compression and decompression under golang. Zlib official method is very simple, here the right as a supplement

Zlib. Newwriter() can only pass data of type [] byte. Newwriter level can pass compression level


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 address

import "compress/zlib"

Write in


func NewWriter
 
  func NewWriter(w io.Writer) *Writer

Read compressed data


func NewReader
 
  func NewReader(r io.Reader) (io.ReadCloser, error)

Set compression level and compress data

func NewWriterLevel(w io.Writer, level int) (io.WriteCloser, os.Error)

Here are several 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)

Close


func (*Writer) Close
 
  func (z *Writer) Close() error

The efficiency and performance of golang zlib compression are OK, after all, Rsync is also using this compression algorithm. In fact, compared with gzip, zlib seems to use more gzip. For example, gzip compression of nginx. I’ve seen a post abroad before that zlib is more suitable for the scene where the speed and compression effect are balanced than gzip.

Recommended Today

Python basics Chinese series tutorial · translation completed

Original: Python basics Python tutorial Protocol: CC by-nc-sa 4.0 Welcome anyone to participate and improve: a person can go very fast, but a group of people can go further. Online reading Apache CN learning resources catalog introduce Seven reasons to learn Python Why Python is great Learn Python introduction Executing Python scripts variable character string […]