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 manipulates operating-system file paths. Use it for filesystem paths; path always uses forward slashes, as in URLs, on every operating system.

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 cleans path syntax but does not confine access to a directory. For untrusted paths, validate that the resolved path stays within the allowed root and account for symlinks. filepath.WalkDir is the standard choice for traversing a directory tree.

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