如何在字符串上使用gzip?

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.

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.