func ExampleWriter_RegisterCompressor() { // Override the default Deflate compressor with a higher compression // level. // Create a buffer to write our archive to. buf := new(bytes.Buffer) // Create a new zip archive. w := zip.NewWriter(buf) var fw *flate.Writer // Register the deflator. w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { var err error if fw == nil { // Creating a flate compressor for every file is // expensive, create one and reuse it. fw, err = flate.NewWriter(out, flate.BestCompression) } else { fw.Reset(out) } return fw, err }) // Proceed to add files to w. }
// Step 1: compresses buffer to buffer // Step 2: send writer to channel // Step 3: Close result channel to indicate we are done func compressBlock(p, prevTail []byte, z Writer, r result) { defer close(r.result) buf := make([]byte, 0, len(p)) dest := bytes.NewBuffer(buf) var compressor *flate.Writer var err error if len(prevTail) > 0 { compressor, err = flate.NewWriterDict(dest, z.level, prevTail) } else { compressor, err = flate.NewWriter(dest, z.level) } if err != nil { z.pushError(err) return } compressor.Write(p) err = compressor.Flush() if err != nil { z.pushError(err) return } if z.closed { err = compressor.Close() if err != nil { z.pushError(err) return } } // Read back buffer buf = dest.Bytes() r.result <- buf }