2021-08-26 18:50:14 +08:00
|
|
|
/**
|
2022-10-31 17:22:49 +08:00
|
|
|
* @Author: Echo
|
|
|
|
* @Email: 1711788888@qq.com
|
2021-08-26 18:50:14 +08:00
|
|
|
* @Date: 2021/8/26 4:59 下午
|
|
|
|
* @Desc: TODO
|
|
|
|
*/
|
|
|
|
|
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Exists check if the file or path exists.
|
|
|
|
func Exists(path string) bool {
|
|
|
|
if stat, err := os.Stat(path); stat != nil && !os.IsNotExist(err) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// SaveToFile save data to file.
|
|
|
|
func SaveToFile(path string, data []byte) error {
|
|
|
|
dir := filepath.Dir(path)
|
|
|
|
if !Exists(dir) {
|
|
|
|
if err := MakeDir(dir); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2022-10-31 17:22:49 +08:00
|
|
|
|
2021-08-26 18:50:14 +08:00
|
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0666))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
2022-10-31 17:22:49 +08:00
|
|
|
|
2021-08-26 18:50:14 +08:00
|
|
|
if n, err := f.Write(data); err != nil {
|
|
|
|
return err
|
|
|
|
} else if n < len(data) {
|
|
|
|
return io.ErrShortWrite
|
|
|
|
}
|
2022-10-31 17:22:49 +08:00
|
|
|
|
2021-08-26 18:50:14 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// MakeDir create directories recursively.
|
|
|
|
func MakeDir(dir string) error {
|
|
|
|
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RealPath get the real path.
|
|
|
|
func RealPath(path string) string {
|
|
|
|
p, err := filepath.Abs(path)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
if !Exists(p) {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return p
|
|
|
|
}
|