代码拉取完成,页面将自动刷新
同步操作将从 shxsun/gohttpserver 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
dkignore "github.com/codeskyblue/dockerignore"
)
type Zip struct {
*zip.Writer
}
func sanitizedName(filename string) string {
if len(filename) > 1 && filename[1] == ':' &&
runtime.GOOS == "windows" {
filename = filename[2:]
}
filename = strings.TrimLeft(strings.Replace(filename, `\`, "/", -1), `/`)
filename = filepath.ToSlash(filename)
filename = filepath.Clean(filename)
return filename
}
func statFile(filename string) (info os.FileInfo, reader io.ReadCloser, err error) {
info, err = os.Lstat(filename)
if err != nil {
return
}
// content
if info.Mode()&os.ModeSymlink != 0 {
var target string
target, err = os.Readlink(filename)
if err != nil {
return
}
reader = ioutil.NopCloser(bytes.NewBuffer([]byte(target)))
} else if !info.IsDir() {
reader, err = os.Open(filename)
if err != nil {
return
}
} else {
reader = ioutil.NopCloser(bytes.NewBuffer(nil))
}
return
}
func (z *Zip) Add(relpath, abspath string) error {
info, rdc, err := statFile(abspath)
if err != nil {
return err
}
defer rdc.Close()
hdr, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
hdr.Name = sanitizedName(relpath)
if info.IsDir() {
hdr.Name += "/"
}
hdr.Method = zip.Deflate // compress method
writer, err := z.CreateHeader(hdr)
if err != nil {
return err
}
_, err = io.Copy(writer, rdc)
return err
}
func CompressToZip(w http.ResponseWriter, rootDir string) {
rootDir = filepath.Clean(rootDir)
zipFileName := filepath.Base(rootDir) + ".zip"
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", `attachment; filename="`+zipFileName+`"`)
zw := &Zip{Writer: zip.NewWriter(w)}
defer zw.Close()
filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
zipPath := path[len(rootDir):]
return zw.Add(zipPath, path)
})
}
func ExtractFromZip(zipFile, path string, w io.Writer) (err error) {
cf, err := zip.OpenReader(zipFile)
if err != nil {
return
}
defer cf.Close()
rd := ioutil.NopCloser(bytes.NewBufferString(path))
patterns, err := dkignore.ReadIgnore(rd)
if err != nil {
return
}
for _, file := range cf.File {
matched, _ := dkignore.Matches(file.Name, patterns)
if !matched {
continue
}
rc, er := file.Open()
if er != nil {
err = er
return
}
defer rc.Close()
_, err = io.Copy(w, rc)
if err != nil {
return
}
return
}
return fmt.Errorf("File %s not found", strconv.Quote(path))
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。