ffcb1a77b9
对 60 个非测试源文件做文档/注释/代码一致性审查,修复 23 项。全部为注释/文档 改动 + 1 处死代码删除,无运行逻辑变更,无 breaking change。 A 档·实质错误(10 项,会误导下游): - app.go: closeResources 三连契约注释统一修正--failAfterInit 走 rollbackReplacedResources 不走 closeResources,closeResources 仅供 doShutdown 复用 - database/manager.go: RandomPicker 注释从过时的 rand.Intn/issue 54899 改为 crypto/rand - model/base.go: datetime(0) 与“亚秒精度”矛盾,改为 datetime(6) - cache/keybuilder.go: 三处示例下划线分隔符改为冒号(与默认分隔符 : 一致) - repository/repository.go: Delete 接口注释从绝对“软删除”改为条件性; UpdateFields 示例移除把字段名当 WHERE 条件的误用写法 - middleware/csrf.go: CSRFToken 注释从“用于 API 模式”改为 Cookie/双重提交模式说明 - examples/full/main.go: POST /users 补上“需 Authorization”标注;删除 _ = app 死代码 - utils/random.go: RandInt/RandInt64 补 min==max 边界说明(对齐 RandIntSecure 写法) B 档·导出符号注释缺失/不完整(6 项): - ws/ws.go: 5 个 Type* 常量、4 个 Err* 变量补注释 - console/console.go: 5 个 Level 常量补注释 - jwt/jwt.go: 2 个 Blacklist 常量补注释 - router/router.go: 包级 GroupWithMiddlewareGroup 补注释 - middleware/ratelimit.go: NewRateLimiter 补 panic 条件与 Stop 生命周期说明 C 档·描述不完整(7 项): - utils/strings.go Substr、convert.go CalcPageCount/CalcOffset、datetime.go StartOfMonth/EndOfMonth、file.go CopyFile、validator.go IsChinese、crypto.go HashFile 补全边界/默认行为/返回值语义 - response/error.go: WithDetail 补 nil 接收者行为说明 验证:go build / go vet / go test -race 全绿。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
126 lines
3.8 KiB
Go
126 lines
3.8 KiB
Go
package utils
|
|
|
|
import (
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
// 本文件提供通用本地文件操作工具(读/写/复制/追加/存在性/删除)。
|
|
//
|
|
// ⚠️ 安全说明(M3):这些函数直接操作调用方传入的路径,不做路径穿越校验。
|
|
// 若路径可能来自不可信输入(用户上传文件名、URL 参数等),调用方必须自行净化
|
|
// (如 filepath.Clean + 前缀锚定),否则存在任意文件读/写/删风险。
|
|
// 框架自身的不可信文件处理(storage 上传/下载)已在 storage 包内做穿越防护(C4)。
|
|
|
|
// FileExists 检查文件是否存在
|
|
func FileExists(path string) bool {
|
|
_, err := os.Stat(path)
|
|
return err == nil
|
|
}
|
|
|
|
// DirExists 检查目录是否存在
|
|
func DirExists(path string) bool {
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return info.IsDir()
|
|
}
|
|
|
|
// EnsureDir 确保目录存在,不存在则创建
|
|
func EnsureDir(path string) error {
|
|
// #nosec G301 -- generic filesystem helper intentionally uses conventional directory permissions; caller controls trusted path and policy.
|
|
return os.MkdirAll(path, 0755)
|
|
}
|
|
|
|
// ReadFile 读取文件内容。
|
|
//
|
|
// M-F 修复:去掉前置 FileExists 检查(TOCTOU 竞态——检查与读取之间文件可能被删除/替换),
|
|
// 直接 os.ReadFile 并返回其错误。文件不存在时返回 *os.PathError,调用方可经
|
|
// errors.Is(err, os.ErrNotExist) 精确判断。
|
|
//
|
|
// 注意:本函数无大小上限(os.ReadFile 语义),读取不可信/超大文件有 OOM 风险——
|
|
// 需限长读取请用 io.ReadAll(io.LimitReader(...));流式哈希大文件请用 HashFile(已流式)。
|
|
func ReadFile(path string) ([]byte, error) {
|
|
// #nosec G304 -- generic filesystem helper intentionally reads caller-provided trusted paths; package docs require callers to sanitize untrusted input.
|
|
return os.ReadFile(path)
|
|
}
|
|
|
|
// WriteFile 写入文件内容(覆盖)
|
|
func WriteFile(path string, data []byte) error {
|
|
dir := filepath.Dir(path)
|
|
if err := EnsureDir(dir); err != nil {
|
|
return err
|
|
}
|
|
// #nosec G306 -- generic filesystem helper intentionally uses conventional file permissions; caller controls trusted path and policy.
|
|
return os.WriteFile(path, data, 0644)
|
|
}
|
|
|
|
// AppendFile 追加内容到文件
|
|
func AppendFile(path string, data []byte) error {
|
|
dir := filepath.Dir(path)
|
|
if err := EnsureDir(dir); err != nil {
|
|
return err
|
|
}
|
|
// #nosec G302,G304 -- generic filesystem helper intentionally appends caller-provided trusted paths with conventional file permissions.
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = f.Write(data)
|
|
if cerr := f.Close(); cerr != nil {
|
|
return errors.Join(err, cerr)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// CopyFile 将 src 复制到 dst(覆盖),自动创建目标目录。src 不存在时返回其 Open 错误。
|
|
func CopyFile(dst, src string) error {
|
|
// #nosec G304 -- generic filesystem helper intentionally opens caller-provided trusted source paths.
|
|
srcFile, err := os.Open(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() {
|
|
_ = srcFile.Close()
|
|
}()
|
|
|
|
// 确保目标目录存在
|
|
dir := filepath.Dir(dst)
|
|
if err := EnsureDir(dir); err != nil {
|
|
return err
|
|
}
|
|
|
|
// #nosec G304 -- generic filesystem helper intentionally creates caller-provided trusted destination paths.
|
|
dstFile, err := os.Create(dst)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = io.Copy(dstFile, srcFile)
|
|
if cerr := dstFile.Close(); cerr != nil {
|
|
return errors.Join(err, cerr)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// FileSize 获取文件大小
|
|
func FileSize(path string) (int64, error) {
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return info.Size(), nil
|
|
}
|
|
|
|
// RemoveFile 删除文件(忽略不存在的错误)
|
|
func RemoveFile(path string) error {
|
|
err := os.Remove(path)
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|