Browse Source

init

master v0.1.0
guzeng 3 years ago
parent
commit
147ec89684
3 changed files with 347 additions and 0 deletions
  1. +50
    -0
      dir.go
  2. +106
    -0
      download.go
  3. +191
    -0
      files.go

+ 50
- 0
dir.go View File

@ -0,0 +1,50 @@
package file
import (
"strings"
)
func Substr(s string, pos, length int) string {
runes := []rune(s)
l := pos + length
if l > len(runes) {
l = len(runes)
}
return string(runes[pos:l])
}
func GetParentDirectory(dirctory, SEPARATOR string) string {
currentDir := strings.TrimRight(dirctory, SEPARATOR)
return Substr(currentDir, 0, strings.LastIndex(currentDir, SEPARATOR))
}
/**
* 创建目录
*/
func CreatePath(path string) error {
DirStat, err := os.Stat(path)
if err != nil || !DirStat.IsDir() {
err := os.MkdirAll(path, 0755)
if err != nil {
log.Println("ERROR|", path, "目录创建失败", err)
}
}
// _, err := os.Stat(path) //检查目录是否存在
// if err != nil {
// cmd := exec.Command("/bin/sh", "-c", "mkdir -p "+path)
// if runtime.GOOS == "windows" {
// cmd = exec.Command("cmd", "/C", "md "+path)
// } else {
// }
// err := cmd.Run()
// return err
// }
return err
}

+ 106
- 0
download.go View File

@ -0,0 +1,106 @@
package file
import (
"errors"
"io"
"net/http"
"os"
"strconv"
)
/**
* 文件是否存在
*/
func IsFileExist(filename string, filesize int64) (bool, error) {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false, err
}
if filesize == info.Size() {
// fmt.Println("已存在!", info.Name(), info.Size(), info.ModTime())
return true, nil
}
err = os.Remove(filename)
return false, err
}
/**
* 文件下载
* param url 要下载的文件URL
* param localPath 文件保存路径或文件保存名称
* fb 回调下载进度
*/
func DownProgress(url string, localPath string, fb func(length, downLen int64)) error {
var (
fsize int64
buf = make([]byte, 32*1024)
written int64
)
tmpFilePath := localPath + ".download"
//创建一个http client
client := new(http.Client)
//client.Timeout = time.Second * 60 //设置超时时间
//get方法获取资源
resp, err := client.Get(url)
if err != nil {
return err
}
//读取服务器返回的文件大小
fsize, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 32)
if err != nil {
// fmt.Println(err)
}
if IsFileExist(localPath, fsize) {
return err
}
//创建文件
file, err := os.Create(tmpFilePath)
if err != nil {
return err
}
defer file.Close()
if resp.Body == nil {
return errors.New("body is null")
}
defer resp.Body.Close()
//下面是 io.copyBuffer() 的简化版本
for {
//读取bytes
nr, er := resp.Body.Read(buf)
if nr > 0 {
//写入bytes
nw, ew := file.Write(buf[0:nr])
//数据长度大于0
if nw > 0 {
written += int64(nw)
}
//写入出错
if ew != nil {
err = ew
break
}
//读取是数据长度不等于写入的数据长度
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
//没有错误了快使用 callback
fb(fsize, written)
}
if err == nil {
file.Close()
err = os.Rename(tmpFilePath, localPath)
}
return err
}

+ 191
- 0
files.go View File

@ -0,0 +1,191 @@
// error debug
package file
import (
"errors"
"io"
"io/ioutil"
"net/http"
"os"
//"os/exec"
"path"
"path/filepath"
//"runtime"
"log"
"strings"
)
/**
* 文件下载
* param url 要下载的文件URL
* param filename 文件保存路径或文件保存名称
*/
func DownloadFile(url, filename string) error {
if url == "" {
return errors.New("文件下载地址为空")
}
//判断filename是路径还是文件名
fileIndex := strings.Index(filename, ".")
var filePath string
if fileIndex < 1 { //名称是路径
index := strings.Index(url, "?")
if index > 0 {
url1 := url[0:index]
index2 := strings.LastIndex(url1, "/")
//修改此处index2为index2+1,不然多了一个多余的/
fileName := url1[index2+1:]
filePath = strings.TrimRight(filename, "/") + "/" + fileName
} else {
fileName := path.Base(url) //获取文件名带后缀
filePath = strings.TrimRight(filename, "/") + "/" + fileName
}
} else {
filePath = filename
}
res, err := http.Get(url)
if err != nil {
return err
}
dir, _ := filepath.Split(filePath)
CreatePath(dir)
file, err := os.Create(filePath)
if err != nil {
return err
}
_, copyerr := io.Copy(file, res.Body)
if copyerr != nil {
return err
}
return nil
}
/**
* 获取远程接口信息
*/
func Geturl(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}
/**
* 文件是否存在
*/
func FileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// Copy a file
func Cpfile(originalFilePath, newFilePath string) error {
// Open original file
originalFile, err := os.Open(originalFilePath)
if err != nil {
return err
}
defer originalFile.Close()
// Create new file
newFile, err := os.Create(newFilePath)
if err != nil {
return err
}
defer newFile.Close()
// Copy the bytes to destination from source
_, err = io.Copy(newFile, originalFile)
if err != nil {
return err
}
// Commit the file contents
// Flushes memory to disk
err = newFile.Sync()
if err != nil {
return err
}
return nil
}
func WriteFile(filePath, data string) error {
fileExist, err := FileExists(filePath)
if err != nil {
return err
}
var f *os.File
if fileExist { //如果文件存在
f, err = os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) //打开文件
} else {
f, err = os.Create(filePath) //创建文件
}
if err != nil {
return err
}
_, err = io.WriteString(f, data) //写入文件(字符串)
if err != nil {
return err
}
return nil
}
/**
* read file
*/
func ReadFile(path string) string {
fi, err := os.Open(path)
if err != nil {
return ""
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
return string(fd)
}
/**
*读取文件内容(返回字符串)
*/
func GetFileContent(FilePath string) string {
buf, err := ioutil.ReadFile(FilePath)
if err != nil {
log.Println("ERROR", "read file error", FilePath, err)
return ""
}
return string(buf)
}

Loading…
Cancel
Save