package file import ( "fmt" "os" "os/exec" "path/filepath" "strings" ) // 当前执行脚本路径 func GetCurPath() string { path, _ := exec.LookPath(os.Args[0]) base := filepath.Base(path) path, _ = filepath.Abs(path) return strings.TrimSuffix(path, "/"+base) } // 项目根路径,携带有项目名称 func GetRootPath() string { dir, _ := os.Getwd() return dir } func GetFilePath(fileName string) (string, error) { // 当前执行脚本路径 var curPath = func() string { path, _ := exec.LookPath(os.Args[0]) path, _ = filepath.Abs(path) return filepath.Dir(path) } // 项目根路径,携带有项目名称 var rootPath = func() string { path, _ := os.Getwd() return path } // 判断文件是否存在 var exist = func(filename string) bool { _, err := os.Stat(filename) return err == nil || os.IsExist(err) } str, _ := filepath.Abs(fileName) if exist(str) { return str, nil } if strings.HasPrefix(fileName, "/") { if !exist(fileName) { return "", fmt.Errorf("%s not fond", fileName) } return fileName, nil } path1 := filepath.Clean(fmt.Sprintf("%s/%s", rootPath(), fileName)) if !exist(path1) { path2 := filepath.Clean(fmt.Sprintf("%s/%s", curPath(), fileName)) if !exist(path2) { return "", fmt.Errorf("%s and %s not fond", path1, path2) } return path2, nil } return path1, nil }