Transparent (filtering) gzip / gunzip in Go

I'm trying, just for fun, to connect gzip Writer directly to gzip Reader so that I can write in Writer and read from Reader on the fly. I expected to read exactly what I wrote. I use gzip, but I would like to use this method also with crypto / aes, I suppose it should work very similar, and it can be used with other readers / writers like jpeg, png ...

This is my best option that doesn't work, but I hope you can see what I mean: http://play.golang.org/p/7qdUi9wwG7

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
)

func main() {
    s := []byte("Hello world!")
    fmt.Printf("%s\n", s)

    var b bytes.Buffer

    gz := gzip.NewWriter(&b)
    ungz, err := gzip.NewReader(&b)
    fmt.Println("err: ", err)

    gz.Write(s)
    gz.Flush()
    uncomp := make([]byte, 100)
    n, err2 := ungz.Read(uncomp)
    fmt.Println("err2: ", err2)
    fmt.Println("n: ", n)
    uncomp = uncomp[:n]
    fmt.Printf("%s\n", uncomp)
}

It seems to be gzip.NewReader(&b)trying to read right away and EOF is returning.

+4
source share
2 answers

, .

  • io.Pipe, -
  • goroutines. , gzip, , , , .

func main() {
    s := []byte("Hello world!")
    fmt.Printf("%s\n", s)

    in, out := io.Pipe()

    gz := gzip.NewWriter(out)
    go func() {
        ungz, err := gzip.NewReader(in)
        fmt.Println("err: ", err)
        uncomp := make([]byte, 100)
        n, err2 := ungz.Read(uncomp)
        fmt.Println("err2: ", err2)
        fmt.Println("n: ", n)
        uncomp = uncomp[:n]
        fmt.Printf("%s\n", uncomp)
    }()
    gz.Write(s)
    gz.Flush()    
}
+5

. ,

io

func Pipe

func Pipe() (*PipeReader, *PipeWriter)

Pipe . , io.Reader , io.Writer. , ; . Close. -. Write, : .

+3

All Articles