skip to Main Content

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? %tn", 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:UsersMohammadMusicUncategorizedTelegram and is it abs? false

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

3

Answers


  1. 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.

    Login or Signup to reply.
  2. For windows os you can use

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

    or

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

    they should work perfectly in your case.

    Login or Signup to reply.
  3. While path.IsAbs "simply checks if the first character of the path is /." as mentioned in another answer, filepath.IsAbs
    actually does checks regarding beginning with a volume, etc. for Windows. As such filepath.IsAbs might be what you want to use in this case

    // IsAbs reports whether the path is absolute.
    func IsAbs(path string) (b bool) {
        if isReservedName(path) {
            return true
        }
        l := volumeNameLen(path)
        if l == 0 {
            return false
        }
        // If the volume name starts with a double slash, this is a UNC path.
        if isSlash(path[0]) && isSlash(path[1]) {
            return true
        }
        path = path[l:]
        if path == "" {
            return false
        }
        return isSlash(path[0])
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search