path.IsAbs returning incorrect result for Windows paths


Documentation of path.IsAbs says that IsAbs reports whether the path is absolute. I have a function in my code that checks if first argument is absolute and if it’s not, it creates an absolute path.

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

The output is first arg -> C:\Users\Mohammad\Music\Uncategorized\Telegram and is it abs? false

But the first argument is absolute, so where I’m missing?


Looking at the 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 it explicitly says:

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.

Thus, follow the documentation and use the correct package for your specific use case.

Answered By – Steffen Ullrich

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.