Home  >  Article  >  Backend Development  >  Compress one byte slice into another slice in Golang

Compress one byte slice into another slice in Golang

王林
王林forward
2024-02-12 16:57:051129browse

在 Golang 中将一个字节切片压缩到另一个切片中

Question content

I want to achieve the exact opposite effect of the solution given here, compress one byte fragment into another byte fragment -

Convert compressed []byte to decompressed []byte golang code

Similar to -

func ZipBytes(unippedBytes []byte) ([]byte, error) {
// ...
}

[I will upload this compressed file as multi-part form data for post requests]

Solution

You can use bytes.buffer to compress directly into memory .

The following example uses compress/zlib because it is the opposite of the example given in the question. Depending on your use case you can also easily change it to compress/gzip (very similar api).

package data_test

import (
    "bytes"
    "compress/zlib"
    "io"
    "testing"
)

func compress(buf []byte) ([]byte, error) {
    var out bytes.Buffer
    w := zlib.NewWriter(&out)
    if _, err := w.Write(buf); err != nil {
        return nil, err
    }
    if err := w.Close(); err != nil {
        return nil, err
    }
    return out.Bytes(), nil
}

func decompress(buf []byte) (_ []byte, e error) {
    r, err := zlib.NewReader(bytes.NewReader(buf))
    if err != nil {
        return nil, err
    }
    defer func() {
        if err := r.Close(); e == nil {
            e = err
        }
    }()
    return io.ReadAll(r)
}

func TestRoundtrip(t *testing.T) {
    want := []byte("test data")

    zdata, err := compress(want)
    if err != nil {
        t.Fatalf("compress: %v", err)
    }
    got, err := decompress(zdata)
    if err != nil {
        t.Fatalf("decompress: %v", err)
    }
    if !bytes.Equal(want, got) {
        t.Errorf("roundtrip: got = %q; want = %q", got, want)
    }
}

The above is the detailed content of Compress one byte slice into another slice in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete