github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/server/utils/download.go (about) 1 package serverUtils 2 3 import ( 4 "archive/zip" 5 "errors" 6 "fmt" 7 "io" 8 "net/http" 9 "os" 10 "strings" 11 "time" 12 13 i118Utils "github.com/easysoft/zendata/pkg/utils/i118" 14 logUtils "github.com/easysoft/zendata/pkg/utils/log" 15 "github.com/mholt/archiver/v3" 16 ) 17 18 func Download(uri string, dst string) error { 19 if strings.Index(uri, "?") < 0 { 20 uri += "?" 21 } else { 22 uri += "&" 23 } 24 uri += fmt.Sprintf("&r=%d", time.Now().Unix()) 25 26 res, err := http.Get(uri) 27 if err != nil { 28 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("download_fail", uri, err.Error())) 29 } 30 defer res.Body.Close() 31 bytes, err := io.ReadAll(res.Body) 32 if err != nil { 33 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("download_read_fail", uri, err.Error())) 34 } 35 36 err = os.WriteFile(dst, bytes, 0666) 37 if err != nil { 38 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("download_write_fail", dst, err.Error())) 39 } else { 40 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("download_success", uri, dst)) 41 } 42 43 return err 44 } 45 46 func GetZipSingleDir(path string) string { 47 folder := "" 48 z := archiver.Zip{} 49 err := z.Walk(path, func(f archiver.File) error { 50 if f.IsDir() { 51 zfh, ok := f.Header.(zip.FileHeader) 52 if ok { 53 //logUtils.PrintTo("file: " + zfh.Name) 54 55 if folder == "" && zfh.Name != "__MACOSX" { 56 folder = zfh.Name 57 } else { 58 if strings.Index(zfh.Name, folder) != 0 { 59 return errors.New("found more than one folder") 60 } 61 } 62 } 63 } 64 return nil 65 }) 66 67 if err != nil { 68 return "" 69 } 70 71 return folder 72 }