Golang使用zip压缩文件


package main

import (
	"archive/zip"
	"io"
	"os"
)

func main() {
	compress("01.png", "01.zip")
}

func compress(file string, dest string) error {
        f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()

	d, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer d.Close()

	wr := zip.NewWriter(d)
	defer wr.Close()

	w, err := wr.Create(file)
	if err != nil {
		return err
	}

	_, err = io.Copy(w, f)
	if err != nil {
		return err
	}

	return nil
}