gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:38:08 25 4
gpt4 key购买 nike

我正在尝试,只是为了好玩,将 gzip Writer 直接连接到 gzip Reader,这样我就可以动态地写入 Writer 并从 Reader 读取。我希望能准确阅读我写的内容。我正在使用 gzip,但我也想将此方法与 crypto/aes 一起使用,我想它的工作方式应该非常相似,并且可以与其他读取器/写入器一起使用,例如 jpeg、png...

这是我最好的选择,它不起作用,但我希望你能明白我的意思: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)
}

似乎 gzip.NewReader(&b) 正在尝试立即读取并返回 EOF。

最佳答案

你需要做两件事来让它工作

  1. 使用io.Pipe将读取器和写入器连接在一起——你不能从同一个缓冲区读取和写入
  2. 在单独的 goroutine 中运行读取和写入。因为 gzip 所做的第一件事是尝试读取 header ,除非您有另一个 go 例程尝试写入它,否则您将遇到死锁。

这是它的样子

Playground

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()
}

关于go - Go 中的透明(类似过滤器)gzip/gunzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20056419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com