Standard library / compress/gzip

compress/gzip.Writer

GZIP compressor embedding Header. Set metadata before the first Write, Flush or Close; Close finalizes the stream without closing the destination. Expected stdout: 'demo Go\n'.

Formal Syntax & Structure

go syntaxgo
type Writer struct {  Header
  // Has unexported fields.}

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 := gzip.NewWriter(&b)  w.Name = "demo"  _, e := w.Write([]byte("Go"))  must(e)  must(w.Close())  r, e := gzip.NewReader(&b)  must(e)  p, e := io.ReadAll(r)  must(e)  must(r.Close())  fmt.Println(r.Name, string(p))}
Go Reference