package util import ( "fmt" "net/http" "os" "path/filepath" "strings" ) // DetectFileType 根据返回的二进制内容推断 contentType + 扩展名 func DetectFileType(data []byte) (contentType string, ext string) { if len(data) == 0 { return "application/octet-stream", ".bin" } ct := http.DetectContentType(data) 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 "audio/mp4", "audio/x-m4a": return ct, ".m4a" case "video/mp4": return ct, ".mp4" case "video/webm": return ct, ".webm" case "image/png": return ct, ".png" case "image/jpeg": return ct, ".jpg" case "image/gif": return ct, ".gif" case "image/webp": return ct, ".webp" case "application/pdf": return ct, ".pdf" case "text/plain": return ct, ".txt" case "application/json": return ct, ".json" case "application/zip": return ct, ".zip" case "application/octet-stream": return ct, ".bin" default: if parts := strings.Split(ct, "/"); len(parts) == 2 { sub := parts[1] if idx := strings.Index(sub, ";"); idx > 0 { sub = strings.TrimSpace(sub[:idx]) } return ct, "." + sub } return ct, ".bin" } } // SaveTmpResult 将二进制数据写入临时文件 func SaveTmpResult(taskID string, data []byte, ext string) (string, error) { dir := filepath.Join(os.TempDir(), "model-asynch") if err := os.MkdirAll(dir, 0o755); err != nil { return "", fmt.Errorf("创建临时目录失败: %w", err) } if ext == "" { ext = ".bin" } if ext[0] != '.' { ext = "." + ext } path := filepath.Join(dir, fmt.Sprintf("%s%s", taskID, ext)) if err := os.WriteFile(path, data, 0o644); err != nil { return "", fmt.Errorf("写入临时文件失败: %w", err) } return path, nil }