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
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:Thus, follow the documentation and use the correct package for your specific use case.
For windows os you can use
or
they should work perfectly in your case.
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