package main
import (
"archive/tar"
"io"
"os"
"time"
"net/http"
)
func compressFile(file_path string, tw *tar.Writer) error {
fileinfo, err := os.Stat(file_path)
if err != nil {
return err
}
hdr, err := tar.FileInfoHeader(fileinfo, "")
if err != nil {
return err
}
err = tw.WriteHeader(hdr)
if err != nil {
return err
}
f, err := os.Open(file_path)
if err != nil {
return err
}
io.Copy(tw, f)
return nil
}
func compress(path string, tw *tar.Writer) error {
file, err := os.Open(path)
if err != nil {
return err
}
info, err := file.Stat()
if err != nil {
return err
}
if info.IsDir() {
fileInfos, err := file.Readdir(-1)
if err != nil {
return err
}
for _, fi := range fileInfos {
file_path := file.Name() + "/" + fi.Name()
if err != nil {
return err
}
compress(file_path, tw)
}
} else {
compressFile(path, tw)
}
return nil
}
func CompressData(w http.ResponseWriter, req *http.Request) {
tw := tar.NewWriter(w)
defer tw.Close()
compress("/home/fankang/go/demo/tar/data/nginx.tar", tw)
time.Sleep(5*time.Second)
compress("/home/fankang/go/demo/tar/data/nginx1.tar", tw)
time.Sleep(5*time.Second)
compress("/home/fankang/go/demo/tar/data/nginx2.tar", tw)
time.Sleep(5*time.Second)
compress("/home/fankang/go/demo/tar/data/data", tw)
}
func main() {
http.HandleFunc("/data", CompressData)
http.ListenAndServe(":8001", nil)
}