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

用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 为什么安装CSiBridge时出现了这个问题,尝试了很多方法都不行,求详细操作步骤?
  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术