Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use gzip on a string?

Tags:

gzip

go

I want to use Go to read out a chunk from a file, treat it as a string and gzip this chunk. I know how to read from the file and treat it as a string, but when it comes to compress/gzip I am lost.

Should I create an io.writer, which writes to a buf (byte slice), use gzip.NewWriter(io.writer) to get a w *gzip.Writer and then use w.Write(chunk_of_file) to write the chunk of file to buf? Then I would need to treat the string as a byte slice.

like image 822
stian Avatar asked Oct 05 '13 12:10

stian


People also ask

How do I compress a string?

Start by taking the first character of the given string and appending it to the compressed string. Next, count the number of occurrences of that specific character and append it to the compressed string. Repeat this process for all the characters until the end of the string is reached.

How do I enable text compression gzip?

Gzip on Windows Servers (IIS Manager)Open up IIS Manager. Click on the site you want to enable compression for. Click on Compression (under IIS) Now Enable static compression and you are done!

How do you compress and decompress a string in Python?

With the help of gzip. decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip. decompress(s) method. Return : Return decompressed string.


1 Answers

You can just write using gzip.Writer as it implements io.Writer.

Example:

package main

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

func main() {
    var b bytes.Buffer
    gz := gzip.NewWriter(&b)
    if _, err := gz.Write([]byte("YourDataHere")); err != nil {
        log.Fatal(err)
    }
    if err := gz.Close(); err != nil {
        log.Fatal(err)
    }
    fmt.Println(b.Bytes())
}

Go Playground

If you want to set the compression level (Default is -1 from compress/flate) you can use gzip.NewWriterLevel.

like image 61
Intermernet Avatar answered Oct 02 '22 23:10

Intermernet