Private
Public Access
1
0
Files
u-desk/internal/filesystem/fs.go
绝尘 6bee55b96f 新增:SFTP直连+连接池+autoConnect+文件服务器端口自动回退
- SFTP模块:连接/断开/文件CRUD/系统信息采集/base64二进制写入
- 连接池:多服务器同时在线,瞬间切换profile
- autoConnect:启动时自动连接所有非本地服务器
- 端口自动回退:listenWithFallback消除TOCTOU,解决端口冲突崩溃
- 文件服务器URL集中管理:file-server.ts消除8+处硬编码端口
- Sidebar设置面板:添加服务器/自动连接/自动刷新开关
- 修复:validateFilePath越界panic、正则预编译
- 修复:注释准确性(RemoveAll/端口8073/动态端口文档)
2026-05-04 15:33:19 +08:00

69 lines
1.6 KiB
Go

package filesystem
import (
"fmt"
"os/exec"
"path/filepath"
"runtime"
"time"
)
// ========== 辅助函数 ==========
// OpenPath 打开文件或目录(使用系统默认程序)
func OpenPath(path string) error {
// 使用 path.validator 进行验证
validator := NewPathValidator(DefaultConfig())
if err := validator.Validate(path); err != nil && err.IsError {
return fmt.Errorf("路径不安全: %w", err)
}
path = filepath.Clean(path)
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
// Windows: 使用 rundll32 打开文件(更可靠)
// 这种方式比 cmd start 更稳定,支持所有文件类型
cmd = exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", path)
case "darwin":
// macOS: 使用 open 命令
cmd = exec.Command("open", path)
case "linux":
// Linux: 使用 xdg-open 命令
cmd = exec.Command("xdg-open", path)
default:
return fmt.Errorf("不支持的操作系统")
}
// 启动命令(不等待完成)
if err := cmd.Start(); err != nil {
return fmt.Errorf("打开文件失败: %v", err)
}
// 给进程一点时间启动
go func() {
time.Sleep(100 * time.Millisecond)
cmd.Process.Release()
}()
return nil
}
// ========== 工具函数 ==========
// FormatBytes 格式化字节大小为人类可读格式(导出供 sftp 等外部包使用)
func FormatBytes(bytes int64) string {
const unit = 1024
if bytes < unit {
return fmt.Sprintf("%d B", bytes)
}
div, exp := int64(unit), 0
for n := bytes / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.2f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}