fix(common): 新增文件类型检测工具并更新 Redis 依赖

This commit is contained in:
2026-09-03 13:07:27 +08:00
parent 7a94a208c0
commit 20ebcfa60b
10 changed files with 849 additions and 53 deletions
+49
View File
@@ -0,0 +1,49 @@
package utils
import (
"net/http"
"strings"
)
// DetectFileType 根据二进制内容推断 contentType + 扩展名(尽量稳定)。
// 纯 stdlib 实现(http.DetectContentType + 常见类型映射),不依赖模型网关。
// 本函数是统一实现;model-gateway/common/util/files.go 的本地副本后续委托到此处。
func DetectFileType(data []byte) (contentType string, ext string) {
if len(data) == 0 {
return "application/octet-stream", ""
}
ct := http.DetectContentType(data)
// DetectContentType 可能带 charset 等参数:text/plain; charset=utf-8
if idx := strings.Index(ct, ";"); idx > 0 {
ct = strings.TrimSpace(ct[:idx])
}
switch ct {
case "audio/mpeg":
return ct, ".mp3"
case "audio/wave", "audio/wav", "audio/x-wav":
return ct, ".wav"
case "video/mp4":
return ct, ".mp4"
case "image/png":
return ct, ".png"
case "image/jpeg":
return ct, ".jpg"
case "application/pdf":
return ct, ".pdf"
case "text/plain":
return ct, ".txt"
case "application/json":
return ct, ".json"
default:
// 兜底:尝试从 ct 截取 subtype 作为后缀(例如 application/json
if parts := strings.Split(ct, "/"); len(parts) == 2 {
sub := parts[1]
// 避免出现 "plain; charset=utf-8" 之类的后缀
if idx := strings.Index(sub, ";"); idx > 0 {
sub = strings.TrimSpace(sub[:idx])
}
return ct, "." + sub
}
return ct, ""
}
}