Fragment Description:



Writing into a zlib compress capable Writer and reading the compressed data from a zlib uncompress capable Reader.
Yet, automatically piping/streaming from one (pw) to the other (pr) thanks to 'io.Pipe()'.
No buffering, but a synchronous in-memoy pipe!


zlibReaderWriterWithPipe

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:36

/* ... <== see fragment description ... */

package main

import (
    "compress/zlib"
    "fmt"
    "io"
    "io/ioutil"
    "time"
)

func main() {
    defer timeTrack(time.Now(), "task duration:")
    // Streaming from pw to pr
    // Pipe creates a synchronous in-memory pipe.
    // Reads on one end are matched with writes on the other, copying data
    // directly between the two. There is no internal buffering.
    pr, pw := io.Pipe()
    zw := zlib.NewWriter(pw) //a zlib capable writer/compressor into pw
    go func() {
        // writing-compressing into pw, using the zw compressing capable writer.
        n, err := zw.Write([]byte(`{"Name":"Monday","Age":6,"Parents":["John","Mary"],"test":{"prop1":1,"prop2":[1,2]}}`))
        if err != nil {
            fmt.Println("pw.Write with error:", err)
        }
        fmt.Printf("number of bytes written to pw: %d\n---\n", n)
        zw.Close()
        pw.Close()
    }()
    // 'zr' a zlib uncompress capable Reader, reads from pr
    zr, _ := zlib.NewReader(pr)
    // reading the uncompressed data from reader zr
    // signature: func ReadAll(r io.Reader) ([]byte, error)
    content, err := ioutil.ReadAll(zr)
    if err != nil {
        fmt.Println("ioutil.ReadAll(zr) with error:", err)
    }
    fmt.Printf("the value of content is: %s\n---\n", string(content))
}
func timeTrack(start time.Time, name string) {
    elapsed := time.Since(start)
    fmt.Printf("function %s took %v\n", name, elapsed)
}

/* Expected Output:
number of bytes written to pw: 84
the value of content is: {"Name":"Monday","Age":6,"Parents":["John","Mary"],"test":{"prop1":1,"prop2":[1,2]}}
function task duration: took 1.0001ms
*/



Comments