Go gzip 没有输出预期的输出

标签 go gzip

我正在尝试使用 Gzip 压缩字符串并将其解压缩,但它并没有像我预期的那样工作。

我的代码如下,我压缩“hello World”然后读取/解压缩它

  s := []byte("hello world")

  var b bytes.Buffer
  gz := gzip.NewWriter(&b)
  defer gz.Close()
  _, err = gz.Write(s)
  if err != nil {
    panic(err)
  }

  r, err := gzip.NewReader(&b)
  defer r.Close()
  if err != nil {
    panic(err)
  }

  l, _ := r.Read(s)

  log.Println(l)

我希望它返回“hello world”,但它返回 0..

如果我删除 l, _ := r.Read(s) 并将最后一行替换为 log.Println(r) 我会得到这个很有道理

&{{ [] 2042-07-14 02:04:00 +0100 CET  255} 0x1847b780 0x185aa000 0x18400db8 0 0 [31 139 8 0 0 9 110 136 0 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] <nil>}

有人可以解释我错在哪里吗?

我想要的只是压缩一个字符串,稍后返回它的解压结果。

最佳答案

完成写入输出。例如,

package main

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

func main() {
    var b bytes.Buffer

    w := gzip.NewWriter(&b)
    s := []byte("hello world")
    _, err := w.Write(s)
    if err != nil {
        panic(err)
    }
    err = w.Flush()
    if err != nil {
        panic(err)
    }
    err = w.Close()
    if err != nil {
        panic(err)
    }

    r, err := gzip.NewReader(&b)
    if err != nil {
        panic(err)
    }
    defer r.Close()
    t := make([]byte, len(s))
    l, err := r.Read(t)
    if err != nil {
        panic(err)
    }

    log.Println(l, string(t))
}

输出:

2009/11/10 23:00:00 11 hello world

关于Go gzip 没有输出预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24097045/

相关文章:

ssh - 如何永久启动 go server?

mysql - 处理超过 20 条记录时出现问题

go - 在 goroutines 中启动 goroutines 是否可以接受?

go - Etcd - 过时的索引。如何从客户端读取 "X-Etcd-Index"

gzip - 安卓 Volley : gzip response

go - Apache Beam Golang Dataflow 运行暂停

c# - GZip 或 Deflate 用于 HTTP 压缩

javascript - 如何在 node.js 中解压缩 .gz 字符串

c# - 我可以使用 HTTP 模块更改传入 HTTP 请求的内容吗?

python - 在 Python 中读取 .tar.gz 文件