Go by Example

File Paths

Build, split, and clean filesystem paths with filepath; use WalkDir for recursive traversal and validate untrusted paths separately.

The path/filepath package builds and examines paths to files and folders. Use it for filesystem paths because it uses the correct separator for each operating system. The path package always uses forward slashes, which is useful for paths inside URLs.

Join builds a path with the current operating system's separator. Dir, Base, and Ext return common parts of a path.

package main
 
import (
    "fmt"
    "path/filepath"
)
 
func main() {
    name := filepath.Join("data", "reports", "daily.csv")
    fmt.Println(name)
    fmt.Println(filepath.Dir(name))
    fmt.Println(filepath.Base(name))
    fmt.Println(filepath.Ext(name))
}

In production

Join combines path parts and cleans extra separators, but it does not stop a path from reaching outside a chosen folder. If a path comes from a user, check where it leads. A symbolic link is a file or folder that points somewhere else, so check links too. Use filepath.WalkDir to visit each item in a directory tree.

Enjoyed this? Get more software craft delivered to your inbox.