doudi5524 2013-11-18 19:46
浏览 40
已采纳

Go中的透明(类似于过滤器)gzip / gunzip

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

This is my best option, that is not working, 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
", 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
", uncomp)
}

It seems that gzip.NewReader(&b) is trying to read immediately and a EOF is returned.

  • 写回答

2条回答 默认 最新

  • douan6931 2013-11-18 23:52
    关注

    You'll need to do two things to make it work

    1. Use an io.Pipe to connect the reader and writer together - you can't read and write from the same buffer
    2. Run the reading and writing in seperate goroutines. Because the first thing that gzip does is attempt to read the header you'll get a deadlock unless you have another go routine attemting to write it.

    Here is what that looks like

    Playground

    func main() {
        s := []byte("Hello world!")
        fmt.Printf("%s
    ", 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
    ", uncomp)
        }()
        gz.Write(s)
        gz.Flush()    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题