Standard library / compress/gzip
compress/gzip.NewReader()
Read a GZIP header and create a decompressor. Read to EOF and check the returned error to verify the trailer checksum. The input is not closed automatically. Expected stdout: 'Go\n'.
Formal Syntax & Structure
go syntaxgo
func NewReader(r io.Reader) (*Reader, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| r | io.Reader | Compressed input stream. Implement io.ByteReader to avoid unnecessary read-ahead where applicable. |
Return Value
(*Reader, error)
New decompression reader or an error while reading the header.
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() { r, e := gzip.NewReader(bytes.NewReader(pack("Go"))) must(e) p, e := io.ReadAll(r) must(e) must(r.Close()) fmt.Println(string(p))}