package main import ( "bufio" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "os" "path" "strings" "time" . "github.com/linxGnu/goseaweedfs" ) // 判断文件夹是否存在 func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } func CreatePath(path string) (bool, error) { exist, err := PathExists(path) if err != nil { return false, err } if exist { return true, nil } else { // 创建文件夹 err := os.Mkdir(path, os.ModePerm) if err != nil { return false, err } else { return true, err } } } func DownloadFile(durl string, destFileName string, filePath string) { uri, err := url.ParseRequestURI(durl) if err != nil { panic("网址错误") } var filename string if destFileName == "" { filename = path.Base(uri.Path) } else { filename = filePath + "/" + destFileName CreatePath(filePath) } log.Println("[*] Filename " + filename) client := http.DefaultClient client.Timeout = time.Second * 60 //设置超时时间 resp, err := client.Get(durl) if err != nil { log.Println("[*] download error:", err) panic(err) } if resp.ContentLength <= 0 { log.Println("[*] Destination server does not support breakpoint download.") } raw := resp.Body defer raw.Close() file, err := os.Create(filename) defer file.Close() writer := bufio.NewWriter(file) defer writer.Flush() body, err := ioutil.ReadAll(raw) writer.Write(body) if err != nil { panic(err) } } func uploadFile(DocFilePath string, fileUpServer string, fileDownServer string) (string, error) { //6. 上传文件到文件服务器 //DocFilePath := utils.Cfg.MustValue("file", "docDir") + entrustId + "/" + tmpDocName var sw *Seaweed var filer []string if _filer := os.Getenv("GOSWFS_FILER_URL"); _filer != "" { filer = []string{_filer} } sw = NewSeaweed("http", fileUpServer, filer, 2*1024*1024, 5*time.Minute) _, _, fID, err := sw.UploadFile(DocFilePath, "", "") log.Println("FID = ", fID) log.Println("err = ", err) retDocUrl := fileDownServer + "/" + fID //6.1 删除本地文件,释放空间 os.Remove(DocFilePath) //7. 保存住报告URL(由controller层调用生成或修改生成报告记录) return retDocUrl, err } //参数字符串拆分 func getParams(params string) map[string]string { m := make(map[string]string) params = strings.Replace(params, "petrotool://", "", -1) params = strings.Replace(params, "/", "", -1) paramAry := strings.Split(params, "&") for _, v := range paramAry { kv := strings.Split(v, "=") m[kv[0]] = kv[1] } return m } func Copy(src, dst string) (int64, error) { sourceFileStat, err := os.Stat(src) if err != nil { return 0, err } if !sourceFileStat.Mode().IsRegular() { return 0, fmt.Errorf("%s is not a regular file", src) } source, err := os.Open(src) if err != nil { return 0, err } defer source.Close() if ret, _ := PathExists(dst); !ret { os.Remove(dst) } destination, err := os.Create(dst) if err != nil { return 0, err } defer destination.Close() nBytes, err := io.Copy(destination, source) return nBytes, err }