github.com/gogf/gf@v1.16.9/.example/encoding/gcompress/zip.go (about)

     1  package main
     2  
     3  import (
     4  	"archive/zip"
     5  	"fmt"
     6  	"github.com/gogf/gf/encoding/gcompress"
     7  	"io"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  )
    12  
    13  // srcFile could be a single file or a directory
    14  func Zip(srcFile string, destZip string) error {
    15  	zipfile, err := os.Create(destZip)
    16  	if err != nil {
    17  		return err
    18  	}
    19  	defer zipfile.Close()
    20  
    21  	archive := zip.NewWriter(zipfile)
    22  	defer archive.Close()
    23  
    24  	filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
    25  		if err != nil {
    26  			return err
    27  		}
    28  
    29  		header, err := zip.FileInfoHeader(info)
    30  		if err != nil {
    31  			return err
    32  		}
    33  
    34  		header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/")
    35  		// header.Name = path
    36  		if info.IsDir() {
    37  			header.Name += "/"
    38  		} else {
    39  			header.Method = zip.Deflate
    40  		}
    41  
    42  		writer, err := archive.CreateHeader(header)
    43  		if err != nil {
    44  			return err
    45  		}
    46  
    47  		if !info.IsDir() {
    48  			file, err := os.Open(path)
    49  			if err != nil {
    50  				return err
    51  			}
    52  			defer file.Close()
    53  			_, err = io.Copy(writer, file)
    54  		}
    55  		return err
    56  	})
    57  
    58  	return err
    59  }
    60  
    61  func main() {
    62  	src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test`
    63  	dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/test.zip`
    64  	//src := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD`
    65  	//dst := `/Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/README.MD.zip`
    66  	fmt.Println(gcompress.ZipPath(src, dst))
    67  	//fmt.Println(Zip(src, dst))
    68  }