Filepath Clean And Join Normalization
Normalize user-supplied paths with filepath.Clean and Join, compute Rel between trees (a ../../-prefixed path, not an error), and split Base and Dir.
Code
package main
import (
"fmt"
"path/filepath"
)
func main() {
// Clean 规整多余分隔符与相对段,分隔符遵循当前操作系统
fmt.Println(filepath.Clean("configs/../configs//app.yaml"))
// Join 对每段做 Clean:拼路径不再手写斜杠
fmt.Println(filepath.Join("configs", "..", "secrets", "key.txt"))
// Rel 计算从 base 到 target 的相对路径;跨树返回 ../../ 前缀而非报错
rel, err := filepath.Rel("/srv/app", "/srv/app/assets/logo.png")
fmt.Println("rel:", rel, "err:", err)
rel2, err2 := filepath.Rel("/srv/app", "/var/log/app.log")
fmt.Println("rel2:", rel2, "err2:", err2)
// Base/Dir 拆出文件名与目录
fmt.Println(filepath.Base("configs/app.yaml"), filepath.Dir("configs/app.yaml"))
}How the snippet works
Under the hood: the function main.
Applying it
Each run prints the 2 labeled blocks rel:, rel2: in source order.
Output is labeled for readability — expect lines prefixed with rel:, rel2:.
Statements that decide the outcome
rel, err := filepath.Rel("/srv/app", "/srv/app/assets/logo.png")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Filepath Clean And Join Normalization print when run?
- Execute the whole file; each printed line is prefixed with a label like `rel:`, `rel2:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.