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.
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.
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!
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With