Standard library / compress/gzip
compress/gzip.NewWriter()
Create a GZIP compressor with DefaultCompression. Write the payload, then close to finish the compressed member and trailer. Expected stdout: 'Go\n'.
Formal Syntax & Structure
go syntaxgo
func NewWriter(w io.Writer) *WriterParameters & Attributes
| Name | Type | Description |
|---|---|---|
| w | io.Writer | Destination for compressed bytes; closing the compressor does not close this writer. |
Return Value
*Writer
New compression writer using default 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 := gzip.NewWriter(&b) _, e := w.Write([]byte("Go")) must(e) must(w.Close()) fmt.Println(unpack(b.Bytes()))}