Path
Paths point to things—they lead to files and folders. With the path package in the Go language we can handle paths for web sites.
With filepath, meanwhile, we can parse Windows paths on Windows computers. Filepath supports the native path format for the present computer.
To begin we have a URL from Wikipedia. We can call path.Split
to get the file name from the URL. The rest of the path is the directory (the Dir).
Split
is the directory (this excludes the file name at the end).package main import ( "fmt" "path" ) func main() { example := "https://en.wikipedia.org/wiki/Ubuntu_version_history" // Split will get the last part after the last slash. // ... This is the file. // ... The dir is the part before the file. dir, file := path.Split(example) fmt.Println(dir) fmt.Println(file) }https://en.wikipedia.org/wiki/ Ubuntu_version_history
Sometimes we want more specific path parts in a program. We can use methods like Base()
and Dir()
to get parts from a path string
. The Split()
func
is not needed.
package main import ( "fmt" "path" ) func main() { example := "/home/bird" // Base returns the file name after the last slash. file := path.Base(example) fmt.Println(file) // Dir returns the directory without the last file name. dir := path.Dir(example) fmt.Println(dir) }bird /home
Suppose you are running Go on a Windows computer. The filepath module is ideal for parsing paths on Windows—it can handle backslashes.
VolumeName()
func
returns the volume name like C—this is the drive letter.package main import ( "fmt" "path/filepath" ) func main() { fmt.Println("[RUN ON WINDOWS]") // Split into directory and file name. dir, file := filepath.Split("C:\\programs\\test.file") fmt.Println("Dir:", dir) fmt.Println("File:", file) // Get volume (drive letter). volume := filepath.VolumeName("C:\\programs\\test.file") fmt.Println("Volume:", volume) }[RUN ON WINDOWS] Dir: C:\programs\ File: test.file Volume: C:
PathSeparator
Go can tell us the current platform's path separator. This is found in the "os" module, as it is OS-specific. On Windows and Linux this will return different values.
PathSeparator
is a rune
. But we can convert it to a string
easily for concatenation or use in string
methods.package main import ( "fmt" "os" ) func main() { fmt.Println(string(os.PathSeparator)) // Use separator in a concatenation. result := "dir" + string(os.PathSeparator) fmt.Println(result) }/ dir/
Paths can be parsed directly in Go, with loops and char
tests. But the path and filepath packages provide built-in functions that are easier to add.