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.

GoCli Tooling

Code

gosnippet
23 lines
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

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:`.