• golang字段串压缩和解压缩


    golang zlib压缩解压缩

    package main
    
    import (
        "bytes"
        "compress/zlib"
        "fmt"
        "io"
        "os"
    )
    
    //进行zlib压缩
    func DoZlibCompress(src []byte) []byte {
        var in bytes.Buffer
        w := zlib.NewWriter(&in)
        w.Write(src)
        w.Close()
        return in.Bytes()
    }
    
    //进行zlib解压缩
    func DoZlibUnCompress(compressSrc []byte) []byte {
        b := bytes.NewReader(compressSrc)
        var out bytes.Buffer
        r, _ := zlib.NewReader(b)
        io.Copy(&out, r)
        return out.Bytes()
    }
    
    func main() {
        buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207,
            47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147}
        b := bytes.NewReader(buff)
        r, err := zlib.NewReader(b)
        if err != nil {
            panic(err)
        }
        io.Copy(os.Stdout, r)
        r.Close()
    
        zip := DoZlibCompress([]byte("hello, world
    "))
        fmt.Println(zip)
        fmt.Println(string(DoZlibUnCompress(zip)))
    }
    

    golang gzip压缩解压缩

    package main
    
    import (
    	"bytes"
    	"compress/gzip"
    	"encoding/base64"
    	"fmt"
    	"io/ioutil"
    )
    
    func main() {
    	var b bytes.Buffer
    	gz := gzip.NewWriter(&b)
    	if _, err := gz.Write([]byte("hello")); err != nil {
    		panic(err)
    	}
    	if err := gz.Flush(); err != nil {
    		panic(err)
    	}
    	if err := gz.Close(); err != nil {
    		panic(err)
    	}
    	str := base64.StdEncoding.EncodeToString(b.Bytes())
    	fmt.Println("base64 encode: ",str)
    	data, _ := base64.StdEncoding.DecodeString(str)
    	fmt.Println("base64 decode:",data)
    	rdata := bytes.NewReader(data)
    	r, _ := gzip.NewReader(rdata)
    	s, _ := ioutil.ReadAll(r)
    	fmt.Println("源字符串:",string(s))
    }
    

    输出:

    base64 encode:  H4sIAAAAAAAA/8pIzcnJBwAAAP//AQAA//+GphA2BQAAAA==
    base64 decode: [31 139 8 0 0 0 0 0 0 255 202 72 205 201 201 7 0 0 0 255 255 1 0 0 255 255 134 166 16 54 5 0 0 0]
    源字符串: hello
    

    参考链接

    http://xiaorui.cc/archives/3084

    https://www.coder.work/article/1029548

    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    vant框架的select下拉框
    监听滚轴高度
    关于使用iframe的父子页面进行简单的相互传值
    vue监听移动端物理返回
    vue+ElementUI项目中,input只能输入正整数的验证
    移动端公共样式
    协程嵌套协程
    基础知识
    汉化包
    .ui转.py文件命令
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/15127472.html
Copyright © 2020-2023  润新知