path.IsAbs 返回 Windows 路径的错误结果

path.IsAbs returning incorrect result for Windows paths

path.IsAbs 的文档说 IsAbs 报告路径是否是绝对路径。我的代码中有一个函数检查第一个参数是否是绝对的,如果不是,它会创建一个绝对路径。

func getPath() string {
    var dir string
    fmt.Printf("first arg -> %s and is it abs? %t\n", os.Args[1], path.IsAbs(os.Args[1]))
    if path.IsAbs(os.Args[1]) {
        dir = os.Args[1]
    } else {
        var currentDir string
        currentDir = filepath.Dir(os.Args[0])
        dir, _ = filepath.Abs(path.Join(currentDir, os.Args[1]))
    }
    return dir
}

输出为first arg -> C:\Users\Mohammad\Music\Uncategorized\Telegram and is it abs? false

但是第一个参数是绝对的,所以我遗漏了什么?

查看 source code of this function it is obvious that it simply checks if the first character of the path is /. This means it assumes a UNIX style of path and not the Windows style with a drive letter. But this behavior is by design and it is also well documented. Right at the beginning of the documentation 它明确表示:

The path package should only be used for paths separated by forward slashes, such as the paths in URLs. This package does not deal with Windows paths with drive letters or backslashes; to manipulate operating system paths, use the path/filepath package.

因此,请遵循文档并针对您的特定用例使用正确的包。

对于windows os你可以使用

C:\Users\Mohammad\Music\Uncategorized\Telegram 

C:/Users/Mohammad/Music/Uncategorized/Telegram 

它们应该能完美地满足您的需求。