-
Notifications
You must be signed in to change notification settings - Fork 0
xfile
omeyang edited this page Sep 17, 2026
·
1 revision
稳定性:Stable · 覆盖率:96.9% · 源码:
pkg/util/xfile
文件操作工具。重点是路径安全:防 directory traversal、符号链接逃逸等。
- 安全读写文件(拒绝越权路径)
- 原子写入(temp file + rename 模式)
- 路径标准化与校验
import "github.com/omeyang/xkit/pkg/util/xfile"
data, err := xfile.SafeReadFile("/data/configs", "user.json")
// 会拒绝 "../../etc/passwd"
err = xfile.AtomicWriteFile("/data/output.json", data, 0644)| 名称 | 说明 |
|---|---|
SafeReadFile(baseDir, name) ([]byte, error) |
限制在 baseDir 内 |
AtomicWriteFile(path, data, perm) error |
temp + rename |
EnsureDir(path, perm) error |
幂等创建 |
IsSubPath(parent, child) bool |
安全断言 |
-
拒绝
..转义:先filepath.Clean,再判前缀 - 原子写:避免半写状态被读到
- 跨平台:处理 Windows 与 Unix 路径分隔符差异