Reaves.dev

v0.1.0

built using

Phoenix v1.7.12

Golang GZIP

Stephen M. Reaves

::

2022-07-22

How to (de)compress a file in golang with GZIP

Snippets

func Compress(b []byte) ([]byte, error) {
    buf := &bytes.Buffer{}

    // You can choose `gzip.BestSpeed` or `gzip.BestCompression`
    gzipWriter, err := gzip.NewWriterLevel(buf, gzip.BestSpeed)
    if err != nil {
        return nil, err
    }

    _, err := gzipWriter.Write(b)
    if err != nil {
        return nil, err
    }

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

    return buf.Bytes(), nil
}
func DeCompress(b []byte) ([]byte, error) {
	buf := &bytes.Buffer{}
	gReader, err := gzip.NewReader(buf)
	if err != nil {
		return nil, err
	}

	_, err = gReader.Read(b)
	if err != nil {
		return nil, err
	}

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

    return buf.Bytes(), nil
}