普通网友 2019-04-10 00:02
浏览 1201
已采纳

用golang解压缩gzip字符串

I have a string which contains a gzip compressed string, therefore there's no file headers, standard compress/gzip library throws error gzip: invalid header

How can I decompress a gzip compressed string in go?

This is what I'm trying

nbody := "eNorTk0uSi0BAAjRAoc="
rdata := strings.NewReader(nbody)
r,err := gzip.NewReader(rdata)
log.Println(r)
if err != nil {
    log.Fatal(err)
}
s, _ := ioutil.ReadAll(r)
fmt.Println(string(s))
  • 写回答

2条回答 默认 最新

  • duanjinchen5296 2019-04-10 01:00
    关注

    ... I have a string which contains a gzip compressed string

    nbody := "eNorTk0uSi0BAAjRAoc="
    

    This is not a "gzip compressed string". This looks like some base64 encoded data which need to be decoded first. After decoding it is not gzip either but zlib - which is basically the same as gzip (content compressed with deflate algorithm) but with a different file header. Therefore trying to decode it with gzip will not work.

    The following will therefore take your original string, decode it from base64 and decompress it using zlib (not gzip):

    package main
    
    import (
            "bytes"
            "compress/zlib"
            "encoding/base64"
            "fmt"
            "io/ioutil"
    )
    
    func main() {
            b64z := "eNorTk0uSi0BAAjRAoc="
            z, _ := base64.StdEncoding.DecodeString(b64z)
            r, _ := zlib.NewReader(bytes.NewReader(z))
            result, _ := ioutil.ReadAll(r)
            fmt.Println(string(result))  // results in "secret"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大