path/filepath
A path looks like a string and is not one: the separator differs per system, . and .. need resolving, and a join of two clean pieces is not a concatenation. path/filepath is the package for paths on the operating system; path is its sibling for slash paths such as URLs and fs paths.
Join, Dir, Base and Ext
Join puts the pieces together with one separator, Clean resolves the dots and the doubled separators, and Dir, Base and Ext split a path into its parts. Each of them is a pure string operation: nothing is opened or checked.
package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Println("join:", filepath.Join("a", "b", "c.txt"))
fmt.Println("dir:", filepath.Dir("/a/b/c.txt"))
fmt.Println("base:", filepath.Base("/a/b/c.txt"))
fmt.Println("ext:", filepath.Ext("/a/b/c.txt"))
fmt.Println("clean:", filepath.Clean("a//b/../c.txt"))
}
go build -o app main.go && ./app
join: a/b/c.txt
dir: /a/b
base: c.txt
ext: .txt
clean: a/c.txt
Ext keeps the dot and returns an empty string when there is none, and Base of a path that ends in a separator is the last directory name. Clean removed the second slash and the b/.. pair, which is the same normalisation Join applies to its result.
Glob
Glob matches a pattern in one directory: * matches any run of characters except a separator, ? one character and [...] a set. It returns the matches sorted, and a pattern without a meta character is a test whether the file exists. The program creates three files and matches the two text ones.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "glob")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
for _, name := range []string{"a.txt", "b.txt", "c.md"} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(name), 0o644); err != nil {
panic(err)
}
}
matches, err := filepath.Glob(filepath.Join(dir, "*.txt"))
if err != nil {
panic(err)
}
for _, match := range matches {
fmt.Println("match:", filepath.Base(match))
}
fmt.Println("count:", len(matches))
}
go build -o app main.go && ./app
match: a.txt
match: b.txt
count: 2
The markdown file did not match, and the two text files came back in lexical order. Glob does not recurse: dir/*/*.txt matches one level down, and WalkDir is the tool for an unknown depth. An invalid pattern such as [ returns ErrBadPattern.
WalkDir
filepath.WalkDir visits a tree in lexical order and gives the full path, so the program computes the name relative to the root before printing it. The root itself is the first call. The callback can skip a directory with fs.SkipDir and stop the walk with any other error.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "walk")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(filepath.Join(dir, "sub", "b.txt"), []byte("b"), 0o644); err != nil {
panic(err)
}
err = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
fmt.Println("visit:", rel)
return nil
})
fmt.Println("walk error:", err)
}
go build -o app main.go && ./app
visit: .
visit: sub
visit: sub/b.txt
walk error: <nil>
The names are the ones a user would see, with forward slashes because this is Linux; on Windows the same program prints backslashes. The relative form is stable across machines in a way the absolute form is not, which is why a test compares the relative names.
Rel and IsAbs
Rel computes how to get from one path to another, and IsAbs reports whether a path starts at the root. The examples below need no files: a failure of Rel means one path is absolute and the other is not, because a relative result cannot describe that jump.
package main
import (
"fmt"
"path/filepath"
)
func main() {
rel, err := filepath.Rel("/a/b/c", "/a/b/d")
fmt.Println("rel:", rel, "err:", err)
rel, err = filepath.Rel("/a/b", "/a/b/c/d")
fmt.Println("rel:", rel, "err:", err)
fmt.Println("abs:", filepath.IsAbs("/a/b"))
fmt.Println("abs:", filepath.IsAbs("a/b"))
}
go build -o app main.go && ./app
rel: ../d err: <nil>
rel: c/d err: <nil>
abs: true
abs: false
The first result goes up one level and then into d; the second goes down two. A program that shows a path to a user usually wants the relative one, and a program that opens a file wants the absolute one: filepath.Abs makes it from the working directory, and the working directory of a service is not the one a developer had in mind.
Paths are not strings
Three habits keep path code portable. Build with Join instead of dir + "/" + name. Compare cleaned paths, not raw ones, because ./a and a are the same file. And keep user input out of a path without a check: filepath.Join(root, name) with name = "../etc/passwd" leaves the root, and filepath.IsLocal is the test that such a name does not.
On the web side the same rules apply with path instead of filepath: a URL path always uses a slash, and a file server converts it. The next lesson reads the arguments a program was started with, which are often paths.
Exercises
- Join an absolute path with .. and print the result. Which part survives, and why is that the safe behaviour?
- Glob * in a directory with a subdirectory and print the matches. Does the directory appear, and what does that say about the pattern?
- Run Rel with one absolute and one relative path and read the error. What does the message say the two paths have in common?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does filepath.Join do?
Answer
Joins the elements with one separator and cleans the result
It is the only correct way to build a path.
-
What does filepath.Ext return?
Answer
The extension with its dot, or an empty string
A name without a dot has no extension.
-
How deep does Glob search?
Answer
One directory per pattern, no recursion
WalkDir is for an unknown depth.
-
In which order does Glob return matches?
Answer
Sorted
The list is lexical.
-
What is the first path WalkDir visits?
Answer
The root itself
The callback sees the root before its contents.
-
What does returning fs.SkipDir from a WalkDir callback do?
Answer
Skips the rest of that directory
Any other error stops the walk.
-
What does filepath.Rel compute?
Answer
A relative path from one path to another
Both paths must be absolute or both relative.
-
What does filepath.IsAbs report?
Answer
Whether the path starts at the root
It is a pure string test.
-
Why is dir + "/" + name a bug?
Answer
The separator is wrong on Windows and the result is not cleaned
Join handles both.
-
Which test rejects a name that leaves the root?
Answer
filepath.IsLocal
A name with .. is not local.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev