How to Compress Single File in Go - Backup Files Software From Scratch Written in Golang Tutorial #5

preview_player
Показать описание
In this tutorial series #5, we will learn how to compress any single file using Golang programming language with step by step guide. We will be using the .zip file compression in Go.

Installed Packages:

#MaharlikansCode
#CompressFileInGo
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper

Source Codes:
cmd/comfile:

package cmd

import (
"os"
"path"
"path/filepath"
"time"

)

// comfileCmd represents the kom command
var comfileCmd = &cobra.Command{
Use: "comfile",
Short: "Compress any single file",
Long: `comfile command compress any single file using .zip compression format.

Example of a valid directory path in Windows:

Or using the network directories, example:
Args: cobra.MinimumNArgs(2),
Run: func(cmd *cobra.Command, args []string) {
// Use this function to auto detect file path structure.
src := filepath.FromSlash(args[0])
dst := filepath.FromSlash(args[1])

// Compose the zip filename
fnWOext := kopy.FileNameWOExt(filepath.Base(args[0])) // Returns a filename without an extension.
zipFileName := fnWOext + ".zip"

// To make directory path separator a universal, in Linux "/" and in Windows "\" to auto change
// depends on the user's OS using the filepath.FromSlash organic Go's library.
zipDest := filepath.FromSlash(path.Join(args[1], zipFileName))

// Check if same filename is exist or not
if sakto.IsFileExist(zipDest) {
color.Red("compressed file already existed: " + zipDest)
return
}

// Start the process.
msg := `Start compressing the file:`
color.Blue(msg + " " + src)
itrlog.Errorw(msg, "src", src, "dst", dst, "log_time", time.Now().Format(logDTFormat))

// List of Files to compressed.
files := []string{src}

os.MkdirAll(dst, os.ModePerm) // Create the root folder first
if err := kopy.ComFiles(zipDest, files); err != nil {
color.Red(err.Error())
itrlog.Errorw("error", "err", err, "log_time", time.Now().Format(logDTFormat))
return
}

msg = `Done compressing the file:`
color.Green(msg + " " + src)
itrlog.Infow(msg, "src", src, "dst", zipDest, "log_time", time.Now().Format(logDTFormat))
},
}

func init() {
rootCmd.AddCommand(comfileCmd)
}

kopy/ComFiles:

// ComFiles compresses one or many files into a single zip archive file.
func ComFiles(dest string, files []string) error {
newZipFile, err := os.Create(dest)
if err != nil {
return err
}
defer newZipFile.Close()

zipWriter := zip.NewWriter(newZipFile)
defer zipWriter.Close()

// Add files to zip
for _, file := range files {
if err = AddFileToZip(zipWriter, file); err != nil {
return err
}
}
Рекомендации по теме
join shbcf.ru