Path and Utils Packages in Go
Master Go standard library helpers for file paths: `path` vs `path/filepath`, joining and cleaning paths safely across OSes, walking directories, and the `sort` package for ordering slices and searching sorted data.
path vs path/filepath
Use **`path`** when you manipulate URL paths or want forward slashes only (e.g. `path.Join("a", "b")` → `a/b`). Use **`path/filepath`** when you read or write files, build paths for `os.Open`, or need Windows vs Unix separators (`\` vs `/`). Mixing them is a common bug: never use `path.Join` for a path you pass to `os.Stat` on Windows.
1. path — Slash-Separated Paths
Join, Clean, Base, Dir for URL-like paths.
2. path/filepath — OS File Paths
Join and Clean for real files and directories.
Building and Inspecting Paths
**`filepath.Join`** is the primary way to build paths from parts. **`filepath.Abs`** resolves a path relative to the current working directory (or returns an error). **`Base`**, **`Dir`**, and **`Ext`** split a path the same way you would in Node’s `path.basename`, `path.dirname`, and `path.extname`. **`Rel`** finds a relative path from one location to another.
1. Abs, Base, Dir, Ext, Rel
Common path inspection helpers.
2. Match and Glob Patterns
Simple shell-style matching and listing.
Walking Directories
**`filepath.Walk`** is the older API; **`filepath.WalkDir`** uses `fs.DirEntry` and avoids extra `os.Stat` calls when you only need type and name. Return **`filepath.SkipDir`** from the callback to skip a directory’s contents. For a predictable demo, create a temporary folder, add a few files, walk it, then remove it.
1. WalkDir on a Temporary Tree
Visit each file and directory under a root.
The sort Package (Slice Utilities)
Unlike Node’s `util` module (formatting, promisify, etc.), Go keeps small algorithms in focused packages. **`sort`** sorts slices in place: `sort.Ints`, `sort.Strings`, `sort.Float64s`, or **`sort.Slice`** with a less function. **`sort.Search`** finds the position to insert a value in a sorted slice. For newer code, **`slices`** (Go 1.21+) adds helpers like `slices.Sort` and `slices.BinarySearch`—they build on the same ideas.
1. sort.Ints, sort.Strings, sort.Slice
Sort primitives and custom order.
2. sort.Search (Binary Search)
Find insertion index in a sorted slice.