Standard library / compress/gzip

compress/gzip.NewWriterLevel()

Select the compression effort explicitly. Invalid levels return an error before writing; no level guarantees smaller output for every input. Expected stdout: 'Go\n'.

Formal Syntax & Structure

go syntaxgo
func NewWriterLevel(w io.Writer, level int) (*Writer, error)

Parameters & Attributes

NameTypeDescription
wio.WriterDestination for compressed bytes; closing the compressor does not close this writer.
levelintCompression level from the package constants or supported integer range.

Return Value

(*Writer, error)

New compression writer or an error for invalid settings.

Working Example

Example Snippetgo
package main
import (  "bytes"  "compress/gzip"  "fmt"  "io")
func must(e error) {  if e != nil {    panic(e)  }}func pack(s string) []byte {  var b bytes.Buffer  w := gzip.NewWriter(&b)  _, e := w.Write([]byte(s))  must(e)  must(w.Close())  return b.Bytes()}func unpack(b []byte) string {  r, e := gzip.NewReader(bytes.NewReader(b))  must(e)  p, e := io.ReadAll(r)  must(e)  must(r.Close())  return string(p)}func main() {  var b bytes.Buffer  w, e := gzip.NewWriterLevel(&b, gzip.BestSpeed)  must(e)  _, e = w.Write([]byte("Go"))  must(e)  must(w.Close())  fmt.Println(unpack(b.Bytes()))}
Go Reference