Go File Paths
Go provides two packages for working with paths:
1. path: For slash-separated paths (like URLs).
2. path/filepath: For operating system paths (Window's \ vs Linux's /). Most of the time, you should use filepath.
1. Joining Paths
Never use manual string concatenation like dir + "/" + file. Use Join to automatically handle separators based on the OS.
2. Extracting Parts
3. Absolute vs Relative
4. Cleaning Paths
The Clean function removes redundant elements like . (current dir) or .. (parent dir).
Why use filepath?
- Cross-platform: Your code will work on Windows, Linux, and macOS without changes.
- Consistency: It handles trailing slashes and multiple separators (
///) correctly. - Security: Cleaning paths helps prevent "Directory Traversal" attacks (like
../../etc/passwd).