To create a compressed reader or writer with a custom compression level in Go, you can use the compress/gzip
or compress/zlib
packages, which provide functionality for gzip and zlib compression respectively. Here's an example of how you can achieve this:
Compressed Reader:
package main
import (
"compress/gzip"
"fmt"
"io"
"os"
)
func main() {
// Open the input file
inputFile, err := os.Open("input.txt")
if err != nil {
fmt.Println("Failed to open input file:", err)
return
}
defer inputFile.Close()
// Create a gzip reader
gzipReader, err := gzip.NewReader(inputFile)
if err != nil {
fmt.Println("Failed to create gzip reader:", err)
return
}
defer gzipReader.Close()
// Read and print the contents of the compressed file
buf := make([]byte, 1024)
for {
n, err := gzipReader.Read(buf)
if err != nil && err != io.EOF {
fmt.Println("Failed to read from gzip reader:", err)
return
}
if n == 0 {
break
}
fmt.Print(string(buf[:n]))
}
}
Compressed Writer:
package main
import (
"compress/gzip"
"fmt"
"os"
)
func main() {
// Open the output file
outputFile, err := os.Create("output.txt.gz")
if err != nil {
fmt.Println("Failed to create output file:", err)
return
}
defer outputFile.Close()
// Create a gzip writer with custom compression level
gzipWriter, err := gzip.NewWriterLevel(outputFile, gzip.BestCompression)
if err != nil {
fmt.Println("Failed to create gzip writer:", err)
return
}
defer gzipWriter.Close()
// Write content to the compressed file
content := "Hello, World!"
_, err = gzipWriter.Write([]byte(content))
if err != nil {
fmt.Println("Failed to write to gzip writer:", err)
return
}
fmt.Println("Content compressed and written to output file")
}
In both examples, the compress/gzip
package is used. If you want to use zlib compression instead, you can replace the import statement with compress/zlib
and use the zlib.NewReader
or zlib.NewWriterLevel
functions accordingly.