path works on slash-separated paths: URLs, import paths, and anything else that always uses "/". For files on disk, reach for path/filepath instead.
Examples
Join glues elements together and cleans the result, so .. is resolved and duplicate slashes collapse.
fmt.Println(path.Join("a", "b", "..", "c"))
fmt.Println(path.Clean("//a//b/../c/"))
fmt.Println(path.IsAbs("/etc"), path.IsAbs("etc"))Output
a/c
/a/c
true falseBase, Dir, and Ext pull the pieces apart. Split returns the directory and file in one call, with the directory keeping its trailing slash.
p := "/usr/local/bin/go"
fmt.Println(path.Base(p))
fmt.Println(path.Dir(p))
fmt.Println(path.Ext("archive.tar.gz"))
dir, file := path.Split(p)
fmt.Printf("%q %q\n", dir, file)Output
go
/usr/local/bin
.gz
"/usr/local/bin/" "go"Match tests a name against a shell pattern. The star stops at a slash, so it never matches across directory boundaries.
ok, _ := path.Match("*.go", "main.go")
fmt.Println(ok)
// * does not cross a slash
ok, _ = path.Match("*.go", "cmd/main.go")
fmt.Println(ok)Output
true
false| Function | Description |
|---|---|
Join(elem ...string) string path.Join("a", "b", "..", "c") // "a/c" | Joins the elements with slashes and cleans the result. Empty elements are dropped. |
Split(p string) (dir, file string) path.Split("/usr/bin/go") // "/usr/bin/", "go" | Splits after the final slash. dir keeps its trailing slash. |
Base(p string) string path.Base("/usr/bin/go") // "go" | The last element. Returns "." for an empty path and "/" for a path of all slashes. |
Dir(p string) string path.Dir("/usr/bin/go") // "/usr/bin" | Everything but the last element, cleaned. |
Ext(p string) string path.Ext("archive.tar.gz") // ".gz" | The extension including the dot, taken from the final dot in the last element. |
Clean(p string) string path.Clean("//a//b/../c/") // "/a/c" | Removes duplicate slashes, . elements, and resolves .. lexically without touching the filesystem. |
IsAbs(p string) bool | Reports whether the path begins with a slash. |
Match(pattern, name string) (bool, error) path.Match("*.go", "main.go") // true | Reports whether name matches a shell pattern. * does not cross slashes. |
Related: path/filepath os strings