如何在 golang 中 gzip 字符串和 return 字节数组

How to gzip string and return byte array in golang

我的 java 代码如下:

    public static byte[] gzip(String str) throws Exception{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);
    gos.write(str.getBytes("UTF-8"));
    gos.close();
    return baos.toByteArray();
}

如何在 golang 中 gzip 字符串和 return 字节数组作为我的 java 完成?

看看下面的代码片段。游乐场:https://play.golang.org/p/3kXBmQ-c9xE

Golang 在其标准库中拥有一切。检查 https://golang.org/pkg/compress/gzip

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "log"
    "strings"
    "io"
)

func main() {
    s := "Hello, playground"

    // Create source reader
    src := strings.NewReader(s)

    buf := bytes.NewBuffer(nil)

    // Create destination writer
    dst := gzip.NewWriter(buf)

    // copy the content as gzip compressed
    _, err := io.Copy(dst, src)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(buf.String())
}

这是使用标准库 compress/gzip

gzipString 函数的完整示例
package main

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

func gzipString(src string) ([]byte, error) {
    var buf bytes.Buffer
    zw := gzip.NewWriter(&buf)

    _, err := zw.Write([]byte(src))
    if err != nil {
        return nil, err
    }

    if err := zw.Close(); err != nil {
        return nil, err
    }

    return buf.Bytes(), nil
}

func main() {
    gzippedBytes, err := gzipString("")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Zipped out: %v", gzippedBytes)
}