Home »
Golang »
Golang Programs
How to check if a path is an absolute path in Golang?
Given a path, we have to check if a path is an absolute path in Golang.
Submitted by IncludeHelp, on October 28, 2021
In the Go programming language, to check whether the given path is an absolute path or not – we use the IsAbs() function of the path/filepath package. The IsAbs() function true if the given path is an absolute path; false, otherwise.
Syntax:
func IsAbs(path string) bool
Consider the below Golang program demonstrating how to check if a path is an absolute path?
package main
import (
"fmt"
"path/filepath"
)
func main() {
// Defining paths
path1 := "/programs/course1/hello1.go"
path2 := "../programs/course1/hello1.go"
path3 := "C:/programs/course1/hello1.go"
// Calling IsAbs() to check the path
// whether absolute or not
if filepath.IsAbs(path1) {
fmt.Println(path1, " is an absolute path.")
} else {
fmt.Println(path1, " is not an absolute path.")
}
if filepath.IsAbs(path2) {
fmt.Println(path2, " is an absolute path.")
} else {
fmt.Println(path2, " is not an absolute path.")
}
if filepath.IsAbs(path3) {
fmt.Println(path3, " is an absolute path.")
} else {
fmt.Println(path3, " is not an absolute path.")
}
}
Output
/programs/course1/hello1.go is an absolute path.
../programs/course1/hello1.go is not an absolute path.
C:/programs/course1/hello1.go is not an absolute path.
Golang path/filepath Package Programs »