SoFunction
Updated on 2025-03-02

Zip compression program made by go language

Files and directories can be compressed.

package main
import (
  "archive/zip"
  "bytes"
  "fmt"
  "io/ioutil"
  "os"
  "path/filepath"
)
func main() {
  if err := compress(`gopkg`, ``); err != nil {
    (err)
  }
}
// Parameter frm can be a file or directory, and no .zip extension is added to dstfunc compress(frm, dst string) error {
  buf := (make([]byte, 0, 10*1024*1024)) // Create a read and write buffer  myzip := (buf)              // Pack the buffer with a compressor  // Use the Walk method to write all files in the directory to zip  err := (frm, func(path string, info , err error) error {
    var file []byte
    if err != nil {
      return 
    }
    header, err := (info) // Convert file information to zip format    if err != nil {
      return 
    }
    , _ = ((frm), path)
    if !() {
      // Determine the compression algorithm used (this is a built-in registered deflate)       = 8
      file, err = (path) // Get the file content      if err != nil {
        return 
      }
    } else {
      file = nil
    }
    // If there is an error in the above part, it will be returned.    // If an error occurs in the following part, it will directly return the error.    // The purpose is to compress the files in the directory as much as possible, and to ensure the correct format of the zip file    w, err := (header) // Create a record and write file information    if err != nil {
      return err
    }
    _, err = (file) // Non-directory files will write data, and directories will not write data    if err != nil {    // Because the content of the directory may be modified      return err     // The most important thing is that I don't know how to get the contents of the directory file    }
    return nil
  })
  if err != nil {
    return err
  }
  ()        // Turn off the compressor and let the data in the compressor buffer be written to buf  file, err := (dst) // Create zip file  if err != nil {
    return err
  }
  defer ()
  _, err = (file) // Write data in buf to a file  if err != nil {
    return err
  }
  return nil
}

The above is the entire content of this article, I hope you like it.