From c2516dc8ffac9ae186f04b23a1390eb38b245d3d Mon Sep 17 00:00:00 2001 From: lxh2875931338 Date: Tue, 28 Jul 2026 18:43:56 +0800 Subject: [PATCH 1/3] =?UTF-8?q?2.2=E6=B5=8B=E8=AF=95=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=BC=95=E5=85=A5=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db-history.go | 111 ++++++++++++++++++ db.go | 309 +++++++++++++++++++++++++++----------------------- readme.md | 11 +- static/app.js | 26 ++++- 4 files changed, 311 insertions(+), 146 deletions(-) create mode 100644 db-history.go diff --git a/db-history.go b/db-history.go new file mode 100644 index 0000000..076df75 --- /dev/null +++ b/db-history.go @@ -0,0 +1,111 @@ +package main + +// ============================================================ +// db-history.go - Schema 版本声明与字段映射 +// 这是整个迁移引擎的“数据源”,记录每个版本的完整 Schema 定义。 +// 迁移工具通过对比当前 Schema 与目标 Schema 的差异来决定迁移路径。 +// ============================================================ + +// SchemaVersionDef 记录一个 Schema 版本的完整字段定义 +type SchemaVersionDef struct { + Version string // 如 "v1", "v2", "v3" + TableName string // 表名,如 "proxies" + Columns map[string]ColumnDef // 字段名 → 字段定义 +} + +// ColumnDef 描述一个字段的结构 +type ColumnDef struct { + Type string // 如 "INTEGER", "TEXT", "BOOLEAN" + NotNull bool // 是否 NOT NULL + Default string // 默认值表达式(如 "0"、"'CHANGE_ME'") + Primary bool // 是否主键 +} + +// schemaHistory 存储所有已知的 Schema 版本(从旧到新排列) +// 每个版本记录的是“完整的表结构”,而不是增量变更。 +// 新增版本时,在这里追加一条记录即可。 +var schemaHistory = []SchemaVersionDef{ + // v1:初始版本(frpc-console 1.0) + { + Version: "v1", + TableName: "proxies", + Columns: map[string]ColumnDef{ + "id": {Type: "INTEGER", Primary: true}, + "name": {Type: "TEXT", NotNull: true}, + "type": {Type: "TEXT", NotNull: true, Default: "'tcp'"}, + "local_ip": {Type: "TEXT", NotNull: true}, + "local_port": {Type: "INTEGER", NotNull: true}, + "remote_port": {Type: "INTEGER", NotNull: true}, + "enabled": {Type: "INTEGER", NotNull: true, Default: "1"}, + "created_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"}, + "updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"}, + }, + }, + // v2:当前版本(frpc-console 2.0 LTS) + // 注意:wire_protocol_v2 是全局配置(global_config),不在 proxies 表中 + { + Version: "v2", + TableName: "proxies", + Columns: map[string]ColumnDef{ + "id": {Type: "INTEGER", Primary: true}, + "name": {Type: "TEXT", NotNull: true}, + "type": {Type: "TEXT", NotNull: true, Default: "'tcp'"}, + "local_ip": {Type: "TEXT", NotNull: true}, + "local_port": {Type: "INTEGER", NotNull: true}, + "remote_port": {Type: "INTEGER", NotNull: true}, + "enabled": {Type: "INTEGER", NotNull: true, Default: "1"}, + "created_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"}, + "updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"}, + }, + }, + // v3:未来版本(规划中) + // 示例:新增隧道分组、流量统计等字段 + // { + // Version: "v3", + // TableName: "proxies", + // Columns: map[string]ColumnDef{ + // // ... 完整字段定义 + // }, + // }, +} + +// getSchemaDef 根据版本号获取 Schema 定义 +func getSchemaDef(version string) *SchemaVersionDef { + for _, def := range schemaHistory { + if def.Version == version { + return &def + } + } + return nil +} + +// getLatestSchemaDef 获取最新的 Schema 版本定义 +func getLatestSchemaDef() *SchemaVersionDef { + if len(schemaHistory) == 0 { + return nil + } + return &schemaHistory[len(schemaHistory)-1] +} + +// schemaVersionsEqual 判断两个 Schema 版本是否完全相同 +func schemaVersionsEqual(v1, v2 *SchemaVersionDef) bool { + if v1 == nil || v2 == nil { + return false + } + if v1.TableName != v2.TableName { + return false + } + if len(v1.Columns) != len(v2.Columns) { + return false + } + for name, col1 := range v1.Columns { + col2, ok := v2.Columns[name] + if !ok { + return false + } + if col1.Type != col2.Type || col1.NotNull != col2.NotNull || col1.Default != col2.Default { + return false + } + } + return true +} diff --git a/db.go b/db.go index 9e0f969..f14a0d0 100644 --- a/db.go +++ b/db.go @@ -8,6 +8,7 @@ import ( "io" "log" "os" + "sort" "strings" "time" @@ -21,7 +22,7 @@ var DB *sql.DB // ============================================================ const ( - SchemaVersion = "2.0.0" // 当前数据库 Schema 版本,与项目版本同步 + SchemaVersion = "v2" // 当前数据库 Schema 版本(与 schemaHistory 中的版本对应) ) // ============================================================ @@ -41,10 +42,10 @@ type GlobalConfig struct { HeartbeatInterval int `json:"heartbeatInterval"` HeartbeatTimeout int `json:"heartbeatTimeout"` PoolCount int `json:"poolCount"` - WireProtocolV2 bool `json:"wireProtocolV2"` // v2.0 正式启用 + WireProtocolV2 bool `json:"wireProtocolV2"` // v2 协议全局开关 } -// Proxy 隧道表 +// Proxy 隧道表(不含 wire_protocol_v2) type Proxy struct { ID int `json:"id"` Name string `json:"name"` @@ -74,22 +75,19 @@ func InitDB() error { return err } - // ---- 创建所有表 ---- if err := createTables(); err != nil { return err } - // ---- 执行版本迁移 ---- if err := runMigrations(); err != nil { return err } - // ---- 确保 JWT 密钥存在 ---- if err := ensureJwtSecret(); err != nil { return err } - log.Println("✅ 数据库初始化完成 (Schema v" + SchemaVersion + ")") + log.Println("✅ 数据库初始化完成 (Schema " + SchemaVersion + ")") return nil } @@ -152,7 +150,7 @@ func createTables() error { return err } - // 应用配置表(存储 JWT 密钥、Schema 版本等) + // 应用配置表 _, err = DB.Exec(` CREATE TABLE IF NOT EXISTS app_config ( key TEXT PRIMARY KEY, @@ -164,7 +162,7 @@ func createTables() error { return err } - // 初始化默认配置(仅当表为空时) + // 初始化默认配置 var count int DB.QueryRow("SELECT COUNT(*) FROM global_config").Scan(&count) if count == 0 { @@ -188,25 +186,21 @@ func createTables() error { // 迁移引擎 // ============================================================ -// getSchemaVersion 读取当前数据库的 Schema 版本 -func getSchemaVersion() string { +// getCurrentSchemaVersion 读取当前数据库的 Schema 版本 +func getCurrentSchemaVersion() string { var version string err := DB.QueryRow("SELECT value FROM app_config WHERE key = 'schema_version'").Scan(&version) if err != nil { if err == sql.ErrNoRows { - // 没有版本记录 → 首次启动或 v1.x 升级 - // 检查是否已有数据(通过 users 表判断) var count int DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&count) if count > 0 { - // 有用户数据 → 这是 v1.x 升级,标记为 1.5 - return "1.5.0" + return "v1" } - // 全新安装 → 直接标记为当前版本 return SchemaVersion } log.Printf("⚠️ 读取 Schema 版本失败: %v", err) - return "1.5.0" // 保守降级 + return "v1" } return version } @@ -224,11 +218,11 @@ func setSchemaVersion(version string) error { func backupDatabase() (string, error) { src := "./frpc-console.db" if _, err := os.Stat(src); os.IsNotExist(err) { - return "", nil // 数据库不存在,无需备份 + return "", nil } timestamp := time.Now().Format("20060102_150405") - dst := fmt.Sprintf("./frpc-console.db.pre-v%s.%s", SchemaVersion, timestamp) + dst := fmt.Sprintf("./frpc-console.db.pre-%s.%s", SchemaVersion, timestamp) srcFile, err := os.Open(src) if err != nil { @@ -250,68 +244,6 @@ func backupDatabase() (string, error) { return dst, nil } -// runMigrations 执行版本迁移 -func runMigrations() error { - currentVersion := getSchemaVersion() - log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVersion, SchemaVersion) - - if currentVersion == SchemaVersion { - log.Println("✅ Schema 已是最新,无需迁移") - return nil - } - - log.Printf("🔄 检测到版本变更 (%s → %s),开始迁移...", currentVersion, SchemaVersion) - - // ---- 1. 备份数据库 ---- - backupPath, err := backupDatabase() - if err != nil { - return fmt.Errorf("备份数据库失败: %w", err) - } - if backupPath != "" { - log.Printf("📦 备份文件: %s", backupPath) - } else { - log.Println("📦 数据库为空,跳过备份") - } - - // ---- 2. 执行迁移 ---- - // 按照版本号逐个升级 - migrations := []struct { - from string - upgrade func() error - }{ - {"1.5.0", migrateFrom1_5_0}, - {"2.0.0", migrateFrom2_0_0}, // 预留,实际无操作 - } - - applied := 0 - for _, m := range migrations { - if currentVersion == m.from { - log.Printf(" 执行迁移: %s → %s", m.from, SchemaVersion) - if err := m.upgrade(); err != nil { - // 迁移失败,尝试恢复备份 - if backupPath != "" { - log.Printf("❌ 迁移失败,尝试恢复备份: %s", backupPath) - if restoreErr := restoreDatabase(backupPath); restoreErr != nil { - log.Printf("⚠️ 恢复备份失败: %v", restoreErr) - } - } - return fmt.Errorf("迁移失败: %w", err) - } - applied++ - currentVersion = SchemaVersion - break - } - } - - // ---- 3. 更新 Schema 版本 ---- - if err := setSchemaVersion(SchemaVersion); err != nil { - return fmt.Errorf("更新 Schema 版本失败: %w", err) - } - - log.Printf("✅ 迁移完成,应用了 %d 个迁移", applied) - return nil -} - // restoreDatabase 从备份恢复数据库 func restoreDatabase(backupPath string) error { srcFile, err := os.Open(backupPath) @@ -334,76 +266,176 @@ func restoreDatabase(backupPath string) error { return nil } -// ============================================================ -// 迁移函数(各版本) -// ============================================================ +// runMigrations 执行迁移 +func runMigrations() error { + currentVer := getCurrentSchemaVersion() + targetVer := SchemaVersion -// migrateFrom1_5_0: v1.5 → v2.0 -// v1.5 已经有 wire_protocol_v2 字段(灰标占位),v2.0 无需新增字段 -// 但需要确保字段存在(兼容从 v1.0 直接升级的场景) -func migrateFrom1_5_0() error { - log.Println(" 迁移: v1.5.0 → v2.0.0") + log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVer, targetVer) - // 检查并补全 wire_protocol_v2 字段(兼容从 v1.0 直接升级的场景) - cols, err := getCurrentColumns("global_config") - if err != nil { - return fmt.Errorf("获取列信息失败: %w", err) + if currentVer == targetVer { + log.Println("✅ Schema 已是最新,无需迁移") + return nil } - if !contains(cols, "wire_protocol_v2") { - log.Println(" 添加字段: wire_protocol_v2") - _, err := DB.Exec("ALTER TABLE global_config ADD COLUMN wire_protocol_v2 INTEGER NOT NULL DEFAULT 0") - if err != nil { - return fmt.Errorf("添加 wire_protocol_v2 字段失败: %w", err) + log.Printf("🔄 检测到版本变更 (%s → %s),开始迁移...", currentVer, targetVer) + + backupPath, err := backupDatabase() + if err != nil { + return fmt.Errorf("备份数据库失败: %w", err) + } + if backupPath != "" { + log.Printf("📦 备份文件: %s", backupPath) + } + + currentSchema := getSchemaDef(currentVer) + targetSchema := getSchemaDef(targetVer) + + if targetSchema == nil { + return fmt.Errorf("目标 Schema 版本 %s 未在 schemaHistory 中定义", targetVer) + } + + if currentSchema == nil || schemaVersionsEqual(currentSchema, targetSchema) { + log.Println(" 迁移类型: 轻量复制(Schema 无变更)") + } else { + log.Println(" 迁移类型: 重型迁移(Schema 有变更,新建表 + 搬数据)") + if err := heavyMigration(currentSchema, targetSchema); err != nil { + if backupPath != "" { + log.Printf("❌ 迁移失败,尝试恢复备份: %s", backupPath) + if restoreErr := restoreDatabase(backupPath); restoreErr != nil { + log.Printf("⚠️ 恢复备份失败: %v", restoreErr) + } + } + return fmt.Errorf("重型迁移失败: %w", err) } } - log.Println(" ✅ v1.5.0 → v2.0.0 迁移完成") - return nil -} - -// migrateFrom2_0_0: 预留,v2.0 → 未来版本 -func migrateFrom2_0_0() error { - log.Println(" v2.0.0 已是当前版本,无需迁移") - return nil -} - -// ============================================================ -// 辅助函数 -// ============================================================ - -func getCurrentColumns(tableName string) ([]string, error) { - rows, err := DB.Query("PRAGMA table_info(" + tableName + ")") - if err != nil { - return nil, err + if err := setSchemaVersion(targetVer); err != nil { + return fmt.Errorf("更新 Schema 版本失败: %w", err) } - defer rows.Close() + log.Printf("✅ 迁移完成,当前 Schema: %s", targetVer) + return nil +} + +// heavyMigration 重型迁移 +func heavyMigration(oldDef, newDef *SchemaVersionDef) error { + if oldDef == nil { + return fmt.Errorf("旧 Schema 定义为空,无法执行重型迁移") + } + + oldTable := oldDef.TableName + newTable := oldTable + "_new" + + createSQL := buildCreateTableSQL(newTable, newDef) + log.Printf(" 创建新表: %s", newTable) + if _, err := DB.Exec(createSQL); err != nil { + return fmt.Errorf("创建新表失败: %w", err) + } + + insertSQL, err := buildInsertSQL(oldTable, newTable, oldDef, newDef) + if err != nil { + return fmt.Errorf("构建数据迁移 SQL 失败: %w", err) + } + log.Printf(" 迁移数据: %s → %s", oldTable, newTable) + if _, err := DB.Exec(insertSQL); err != nil { + return fmt.Errorf("数据迁移失败: %w", err) + } + + var oldCount, newCount int + DB.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", oldTable)).Scan(&oldCount) + DB.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", newTable)).Scan(&newCount) + if oldCount != newCount { + return fmt.Errorf("数据迁移不完整: 旧表 %d 行,新表 %d 行", oldCount, newCount) + } + log.Printf(" 数据迁移验证通过: %d 行", newCount) + + tempTable := oldTable + "_old_temp" + if _, err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", oldTable, tempTable)); err != nil { + return fmt.Errorf("重命名旧表失败: %w", err) + } + if _, err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", newTable, oldTable)); err != nil { + DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", tempTable, oldTable)) + return fmt.Errorf("重命名新表失败: %w", err) + } + if _, err := DB.Exec(fmt.Sprintf("DROP TABLE %s", tempTable)); err != nil { + log.Printf("⚠️ 删除临时表失败(不影响使用): %v", err) + } + + log.Printf(" 表交换完成: %s (新表已生效)", oldTable) + return nil +} + +// buildCreateTableSQL 根据 Schema 定义生成 CREATE TABLE 语句 +func buildCreateTableSQL(tableName string, def *SchemaVersionDef) string { var cols []string - for rows.Next() { - var ( - cid int - name string - typ string - notNull int - dfltVal sql.NullString - pk int - ) - if err := rows.Scan(&cid, &name, &typ, ¬Null, &dfltVal, &pk); err != nil { - return nil, err - } - cols = append(cols, name) + var primaryKey string + + names := make([]string, 0, len(def.Columns)) + for name := range def.Columns { + names = append(names, name) } - return cols, rows.Err() + sort.Strings(names) + + for _, name := range names { + col := def.Columns[name] + parts := []string{name, col.Type} + if col.NotNull { + parts = append(parts, "NOT NULL") + } + if col.Default != "" { + parts = append(parts, "DEFAULT "+col.Default) + } + if col.Primary { + primaryKey = "PRIMARY KEY (" + name + ")" + } else { + cols = append(cols, strings.Join(parts, " ")) + } + } + + if primaryKey != "" { + cols = append(cols, primaryKey) + } + + return fmt.Sprintf("CREATE TABLE %s (\n %s\n)", tableName, strings.Join(cols, ",\n ")) } -func contains(slice []string, item string) bool { - for _, s := range slice { - if strings.EqualFold(s, item) { - return true +// buildInsertSQL 构建 INSERT INTO new_table SELECT ... FROM old_table +func buildInsertSQL(oldTable, newTable string, oldDef, newDef *SchemaVersionDef) (string, error) { + newCols := make([]string, 0, len(newDef.Columns)) + for name := range newDef.Columns { + newCols = append(newCols, name) + } + sort.Strings(newCols) + + var selectParts []string + var colNames []string + + for _, name := range newCols { + colNames = append(colNames, name) + if _, ok := oldDef.Columns[name]; ok { + selectParts = append(selectParts, name) + } else { + colDef := newDef.Columns[name] + if colDef.Default != "" { + selectParts = append(selectParts, colDef.Default+" AS "+name) + } else if colDef.Type == "INTEGER" { + selectParts = append(selectParts, "0 AS "+name) + } else if colDef.Type == "TEXT" { + selectParts = append(selectParts, "'' AS "+name) + } else { + selectParts = append(selectParts, "NULL AS "+name) + } } } - return false + + return fmt.Sprintf( + "INSERT INTO %s (%s) SELECT %s FROM %s", + newTable, + strings.Join(colNames, ", "), + strings.Join(selectParts, ", "), + oldTable, + ), nil } // ============================================================ @@ -504,10 +536,7 @@ func GetProxies() ([]Proxy, error) { } proxies = append(proxies, p) } - if err = rows.Err(); err != nil { - return nil, err - } - return proxies, nil + return proxies, rows.Err() } func GetProxy(id int) (*Proxy, error) { diff --git a/readme.md b/readme.md index 4fe2d7c..465a1b5 100644 --- a/readme.md +++ b/readme.md @@ -142,7 +142,14 @@ go build -ldflags="-s -w" -o frpc-console . #### Q: frpc 启动失败怎么办? -检查 frpc.toml 配置是否正确,或查看 ./frpc.log 日志文件。 +如果是首次启动,console 会自动生成一份符合官方规范的 `frps.toml` 配置文件,通常不需要额外操作。 + +如果在使用过程中遇到启动失败,可以按以下步骤排查: + +1. **检查配置是否正确** —— 在「全局配置」页面重新配置一次服务端参数,或导入已有的 `frpc.toml` 配置文件,console 会自动应用并尝试重启 +2. **查看日志定位问题** —— 若上述操作后仍然失败,请查看 `./frpc.log` 日志文件,定位具体报错原因 + +> 日志文件的位置:与 `frpc-console` 二进制同级目录下的 `frpc.log`。Docker 部署时,可通过 `docker logs frpc-console` 查看容器输出。 #### Q: 支持哪些 frp 版本? @@ -289,7 +296,7 @@ frpc-console 遵循 **“够用就好”** 的原则: ## 📄 许可证 -MIT License © 2026 Gitea:lxh2875931338/Github:XHLiang0 +MIT License © 2026 lxh2875931338(XHLiang0) --- diff --git a/static/app.js b/static/app.js index a0e0c24..7d3082d 100644 --- a/static/app.js +++ b/static/app.js @@ -28,6 +28,14 @@ async function apiFetch(endpoint, options = {}) { ...options, headers: { ...headers, ...(options.headers || {}) }, }); + + // ---- 统一处理 401 认证失效 ---- + if (res.status === 401) { + clearAuthState(); + window.dispatchEvent(new CustomEvent("auth:expired")); + return { code: 401, msg: "认证已过期,请重新登录" }; + } + return res.json(); } @@ -286,8 +294,16 @@ const app = createApp({ let logTimer = null; let logFetching = false; + // ---- 认证过期处理 ---- + const handleAuthExpired = () => { + doLogout(); + }; + // ---- 初始化 ---- onMounted(() => { + // 监听认证过期事件 + window.addEventListener("auth:expired", handleAuthExpired); + const saved = loadAuthState(); if (saved.valid) { token.value = saved.token; @@ -351,6 +367,11 @@ const app = createApp({ logFetching = true; try { const result = await fetchLogsApi(); + // ---- 如果 API 返回 401,停止轮询(事件已触发登出) ---- + if (result.code === 401) { + logFetching = false; + return; + } logLines.value = result.lines; logTotal.value = result.total; logError.value = result.error; @@ -641,7 +662,6 @@ const app = createApp({ ); const showDefaultTip = computed(() => { - // 如果 serverAddr 还是默认值,或者为空,显示警告 const addr = globalConfig.serverAddr; return !addr || addr === "frp.example.com" || addr.trim() === ""; }); @@ -692,9 +712,8 @@ const app = createApp({ passwordChangeSuccess, changePassword, - showDefaultTip, + showDefaultTip, - // 日志相关 logLines, logTotal, logError, @@ -703,7 +722,6 @@ const app = createApp({ refreshLogs, scrollLogToBottom, - // Token 显示切换 showToken, }; }, From aaac3fc791c7297aa9ce5ea8cfcdc417ed7bdd26 Mon Sep 17 00:00:00 2001 From: lxh2875931338 Date: Tue, 28 Jul 2026 19:11:40 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E5=BC=95=E5=85=A52.1=E5=BA=94=E5=81=9A?= =?UTF-8?q?=E7=9A=84=E5=85=A8=E6=96=B0UI=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api.go | 34 +++++++++++++++++- static/app.js | 87 ++++++++++++++++++++++++++++++++++++++++++++++ static/index.html | 84 ++++++++++++++++++++++++-------------------- static/style-3.css | 66 +++++++++++++++++++++++++++++++++++ 4 files changed, 233 insertions(+), 38 deletions(-) diff --git a/api.go b/api.go index 809d438..2f746f4 100644 --- a/api.go +++ b/api.go @@ -6,11 +6,13 @@ import ( "fmt" "io" "io/fs" + "net" "net/http" "os" "strconv" "strings" "text/template" + "time" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" @@ -64,7 +66,7 @@ func SetupRouter() *gin.Engine { auth.POST("/frpc/stop", stopFrpcHandler) auth.GET("/frpc/status", getFrpcStatusHandler) auth.GET("/frpc/log", getFrpcLogHandler) - + auth.GET("/ping", pingHandler) auth.POST("/import/toml", importTomlHandler) auth.GET("/export/toml", ExportTomlHandler) @@ -143,6 +145,36 @@ func registerHandler(c *gin.Context) { }) } +// Ping 延迟检测 +func pingHandler(c *gin.Context) { + target := c.Query("target") + if target == "" { + c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "缺少 target 参数"}) + return + } + + // 获取全局配置(获取服务端端口) + cfg, err := GetGlobalConfig() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "读取配置失败"}) + return + } + + port := cfg.ServerPort + address := net.JoinHostPort(target, strconv.Itoa(port)) + + start := time.Now() + conn, err := net.DialTimeout("tcp", address, 5*time.Second) + if err != nil { + c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "ping 失败", "latency": -1}) + return + } + conn.Close() + + latency := time.Since(start).Milliseconds() + c.JSON(http.StatusOK, gin.H{"code": 0, "latency": latency}) +} + func loginHandler(c *gin.Context) { var req struct { Username string `json:"username"` diff --git a/static/app.js b/static/app.js index 7d3082d..6a04455 100644 --- a/static/app.js +++ b/static/app.js @@ -205,6 +205,93 @@ async function fetchLogsApi() { } } +// ---- 新增:Ping 延迟检测 ---- +const pingLatency = ref(null); // null 表示未接入/失败 +const pingInterval = ref(null); +const PING_INTERVAL_MS = 30000; // 30 秒轮询一次 +const PING_TIMEOUT_MS = 5000; // 5 秒超时 + +// 计算 ping 状态 class +const pingStatusClass = computed(() => { + if (pingLatency.value === null) return 'ping-fail'; + if (pingLatency.value < 1000) return 'ping-good'; + if (pingLatency.value < 5000) return 'ping-slow'; + return 'ping-fail'; +}); + +// 根据状态返回对应 SVG 图标(内联) +const pingIcon = computed(() => { + if (pingLatency.value === null) { + // 未接入/失败 —— 断开图标 + return ` + + + + + + `; + } + if (pingLatency.value < 1000) { + // 延迟好 —— 实心信号图标(青色/绿色) + return ` + + + `; + } + // 延迟一般(1000-5000ms)—— 空心信号图标(黄色/橙色) + return ` + + + `; +}); + +// 执行 Ping 检测 +async function doPing() { + if (!frpcRunning.value) { + pingLatency.value = null; + return; + } + const addr = globalConfig.serverAddr || 'frp.example.com'; + const start = performance.now(); + try { + const res = await fetch(`/api/ping?target=${encodeURIComponent(addr)}`, { + signal: AbortSignal.timeout(PING_TIMEOUT_MS), + }); + if (!res.ok) throw new Error('Ping failed'); + const end = performance.now(); + pingLatency.value = Math.round(end - start); + } catch { + pingLatency.value = null; + } +} + +// 启动 Ping 轮询 +function startPingPolling() { + if (pingInterval.value) return; + doPing(); + pingInterval.value = setInterval(doPing, PING_INTERVAL_MS); +} + +function stopPingPolling() { + if (pingInterval.value) { + clearInterval(pingInterval.value); + pingInterval.value = null; + } +} + +// 在登录后启动,退出时停止 +// 在 loadAllData 成功后调用 startPingPolling() +// 在 doLogout 中调用 stopPingPolling() +// 监听 frpcRunning 变化:如果为 false,清空 pingLatency +watch(frpcRunning, (running) => { + if (!running) { + pingLatency.value = null; + stopPingPolling(); + } else if (loggedIn.value) { + startPingPolling(); + } +}); + // ============================================================ // 7. UI State // ============================================================ diff --git a/static/index.html b/static/index.html index bef17dc..63de43e 100644 --- a/static/index.html +++ b/static/index.html @@ -87,7 +87,6 @@
-
@@ -97,11 +96,17 @@ {{ frpcRunning ? 'frpc 运行中' : 'frpc 已停止' }} + + + + + {{ pingLatency !== null ? pingLatency + 'ms' : '--ms' + }} +
- {{ loginForm.username }}
@@ -114,6 +119,8 @@ @click="activeTab = 'config'">全局配置信息 运行日志 + 用户配置:{{loginForm.username }} @@ -159,7 +166,6 @@ -
@@ -170,34 +176,7 @@
- 首次使用请修改「服务器地址」和「认证令牌」为您的真实 frpc 配置 -
- - -
-
- 账户管理 - {{ loginForm.username }} -
-
-
- - -
-
- - -
-
- - -
- - - -
+ 首次使用请修改「服务器地址」和「认证令牌」为您的真实 frps 配置
@@ -242,31 +221,27 @@ 优化连接性能,减少延迟,frp 官方推荐开启
-
-
-
-
- +
-
+ +
@@ -339,6 +316,39 @@
+ +
+
+

用户配置:{{ loginForm.username }}

+

修改当前账户的登录密码

+
+ +
+
+ 账户管理 + {{ loginForm.username }} +
+
+
+ + +
+
+ + +
+
+ + +
+ + + +
+
+
diff --git a/static/style-3.css b/static/style-3.css index 73a3c6b..c0b3a59 100644 --- a/static/style-3.css +++ b/static/style-3.css @@ -734,4 +734,70 @@ select:disabled { .dialog-card { padding: 20px; } +} + +/* ---------- Ping 延迟显示 ---------- */ +.status-wrapper { + display: flex; + align-items: center; + gap: 12px; +} + +.ping-display { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 12px; + font-weight: 500; + padding: 2px 8px 2px 4px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.04); + transition: background 0.3s; +} + +.ping-display .ping-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; +} + +.ping-display .ping-icon svg { + width: 100%; + height: 100%; +} + +/* 状态颜色 */ +.ping-good .ping-icon { + color: #63e2b7; +} +.ping-good .ping-value { + color: #63e2b7; +} + +.ping-slow .ping-icon { + color: #f0c040; +} +.ping-slow .ping-value { + color: #f0c040; +} + +.ping-fail .ping-icon { + color: #f87171; +} +.ping-fail .ping-value { + color: #f87171; +} + +/* 响应式调整 */ +@media (max-width: 768px) { + .ping-display { + font-size: 11px; + padding: 1px 6px 1px 2px; + } + .ping-display .ping-icon { + width: 14px; + height: 14px; + } } \ No newline at end of file From babfdee02bcf49b13ae51ae69430a879e24f02c9 Mon Sep 17 00:00:00 2001 From: lxh2875931338 Date: Tue, 28 Jul 2026 19:30:26 +0800 Subject: [PATCH 3/3] =?UTF-8?q?2.2=E6=8A=80=E6=9C=AF=E9=A2=84=E8=A7=88?= =?UTF-8?q?=E7=89=88=E6=9B=B4=E6=96=B0=E5=86=85=E5=AE=B9=E5=B7=B2=E5=86=99?= =?UTF-8?q?=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- static/app.js | 190 +++++++++++++++++++++++----------------------- static/index.html | 87 ++++++++++----------- 2 files changed, 137 insertions(+), 140 deletions(-) diff --git a/static/app.js b/static/app.js index 6a04455..d64c224 100644 --- a/static/app.js +++ b/static/app.js @@ -171,7 +171,7 @@ function filterProxies(list, keyword) { (p) => p.name.toLowerCase().includes(kw) || p.localIP.includes(kw) || - String(p.remotePort).includes(kw) + String(p.remotePort).includes(kw), ); } @@ -197,7 +197,11 @@ async function fetchLogsApi() { try { const data = await apiFetch("/frpc/log"); if (data.code === 0) { - return { lines: data.data.lines || [], total: data.data.total || 0, error: data.data.error || "" }; + return { + lines: data.data.lines || [], + total: data.data.total || 0, + error: data.data.error || "", + }; } return { lines: [], total: 0, error: "加载失败" }; } catch (e) { @@ -205,93 +209,6 @@ async function fetchLogsApi() { } } -// ---- 新增:Ping 延迟检测 ---- -const pingLatency = ref(null); // null 表示未接入/失败 -const pingInterval = ref(null); -const PING_INTERVAL_MS = 30000; // 30 秒轮询一次 -const PING_TIMEOUT_MS = 5000; // 5 秒超时 - -// 计算 ping 状态 class -const pingStatusClass = computed(() => { - if (pingLatency.value === null) return 'ping-fail'; - if (pingLatency.value < 1000) return 'ping-good'; - if (pingLatency.value < 5000) return 'ping-slow'; - return 'ping-fail'; -}); - -// 根据状态返回对应 SVG 图标(内联) -const pingIcon = computed(() => { - if (pingLatency.value === null) { - // 未接入/失败 —— 断开图标 - return ` - - - - - - `; - } - if (pingLatency.value < 1000) { - // 延迟好 —— 实心信号图标(青色/绿色) - return ` - - - `; - } - // 延迟一般(1000-5000ms)—— 空心信号图标(黄色/橙色) - return ` - - - `; -}); - -// 执行 Ping 检测 -async function doPing() { - if (!frpcRunning.value) { - pingLatency.value = null; - return; - } - const addr = globalConfig.serverAddr || 'frp.example.com'; - const start = performance.now(); - try { - const res = await fetch(`/api/ping?target=${encodeURIComponent(addr)}`, { - signal: AbortSignal.timeout(PING_TIMEOUT_MS), - }); - if (!res.ok) throw new Error('Ping failed'); - const end = performance.now(); - pingLatency.value = Math.round(end - start); - } catch { - pingLatency.value = null; - } -} - -// 启动 Ping 轮询 -function startPingPolling() { - if (pingInterval.value) return; - doPing(); - pingInterval.value = setInterval(doPing, PING_INTERVAL_MS); -} - -function stopPingPolling() { - if (pingInterval.value) { - clearInterval(pingInterval.value); - pingInterval.value = null; - } -} - -// 在登录后启动,退出时停止 -// 在 loadAllData 成功后调用 startPingPolling() -// 在 doLogout 中调用 stopPingPolling() -// 监听 frpcRunning 变化:如果为 false,清空 pingLatency -watch(frpcRunning, (running) => { - if (!running) { - pingLatency.value = null; - stopPingPolling(); - } else if (loggedIn.value) { - startPingPolling(); - } -}); - // ============================================================ // 7. UI State // ============================================================ @@ -381,6 +298,80 @@ const app = createApp({ let logTimer = null; let logFetching = false; + // ---- Ping 延迟检测(移到 setup 内部) ---- + const pingLatency = ref(null); + let pingTimer = null; + const PING_INTERVAL_MS = 30000; + const PING_TIMEOUT_MS = 5000; + + const pingStatusClass = computed(() => { + if (pingLatency.value === null) return "ping-fail"; + if (pingLatency.value < 1000) return "ping-good"; + if (pingLatency.value < 5000) return "ping-slow"; + return "ping-fail"; + }); + + const pingIcon = computed(() => { + if (pingLatency.value === null) { + // 未接入/失败 —— 断开图标 + return ` + + + + + + `; + } + if (pingLatency.value < 1000) { + // 延迟好 —— 实心信号图标(青色/绿色) + return ` + + + `; + } + // 延迟一般(1000-5000ms)—— 空心信号图标(黄色/橙色) + return ` + + + `; + }); + + async function doPing() { + // 如果 frpc 未运行,直接显示 --ms + if (!frpcRunning.value) { + pingLatency.value = null; + return; + } + const addr = globalConfig.serverAddr || "frp.example.com"; + const start = performance.now(); + try { + const res = await fetch( + `/api/ping?target=${encodeURIComponent(addr)}`, + { + signal: AbortSignal.timeout(PING_TIMEOUT_MS), + }, + ); + if (!res.ok) throw new Error("Ping failed"); + const end = performance.now(); + pingLatency.value = Math.round(end - start); + } catch { + pingLatency.value = null; + } + } + + function startPingPolling() { + if (pingTimer) return; + doPing(); + pingTimer = setInterval(doPing, PING_INTERVAL_MS); + } + + function stopPingPolling() { + if (pingTimer) { + clearInterval(pingTimer); + pingTimer = null; + } + } + // ---- 认证过期处理 ---- const handleAuthExpired = () => { doLogout(); @@ -388,7 +379,6 @@ const app = createApp({ // ---- 初始化 ---- onMounted(() => { - // 监听认证过期事件 window.addEventListener("auth:expired", handleAuthExpired); const saved = loadAuthState(); @@ -415,6 +405,15 @@ const app = createApp({ } }); + watch(frpcRunning, (running) => { + if (!running) { + stopPingPolling(); + pingLatency.value = null; // 显示 --ms + } else if (loggedIn.value) { + startPingPolling(); + } + }); + async function checkUsers() { try { const res = await fetch("/api/check/users"); @@ -454,7 +453,6 @@ const app = createApp({ logFetching = true; try { const result = await fetchLogsApi(); - // ---- 如果 API 返回 401,停止轮询(事件已触发登出) ---- if (result.code === 401) { logFetching = false; return; @@ -586,6 +584,7 @@ const app = createApp({ const doLogout = () => { if (expireTimer) clearInterval(expireTimer); stopLogPolling(); + stopPingPolling(); contentVisible.value = false; loggedIn.value = false; token.value = ""; @@ -745,7 +744,7 @@ const app = createApp({ // ---- 计算属性 ---- const filteredProxies = computed(() => - filterProxies(proxies.value, searchKeyword.value) + filterProxies(proxies.value, searchKeyword.value), ); const showDefaultTip = computed(() => { @@ -810,8 +809,13 @@ const app = createApp({ scrollLogToBottom, showToken, + + // ---- 新增 Ping 相关导出 ---- + pingLatency, + pingStatusClass, + pingIcon, }; }, }); -app.mount("#app"); \ No newline at end of file +app.mount("#app"); diff --git a/static/index.html b/static/index.html index 63de43e..5ced711 100644 --- a/static/index.html +++ b/static/index.html @@ -87,6 +87,7 @@
+
@@ -96,12 +97,10 @@ {{ frpcRunning ? 'frpc 运行中' : 'frpc 已停止' }} - - + - {{ pingLatency !== null ? pingLatency + 'ms' : '--ms' - }} + {{ pingLatency !== null ? pingLatency + 'ms' : '--ms' }}
@@ -168,18 +167,16 @@
-

全局配置信息

管理 frpc 连接参数与传输设置

-
首次使用请修改「服务器地址」和「认证令牌」为您的真实 frps 配置
- +
服务器连接 @@ -206,13 +203,12 @@
- +
传输配置
-
@@ -237,7 +233,6 @@
-
@@ -253,7 +248,7 @@
- +
日志配置 @@ -276,14 +271,11 @@
-
-
-
共 {{ logTotal }} 行 @@ -299,7 +291,6 @@
-
暂无日志,frpc 尚未产生输出 @@ -309,7 +300,6 @@
-
-
-
-
- - -
-
-

{{ dialogMode === 'add' ? '新增隧道' : '编辑隧道' }}

-
-
-
- - -
-
-
-
-
+
+ + + +
+
+

{{ dialogMode === 'add' ? '新增隧道' : '编辑隧道' }}

+
+
+
+ + +
+
+
+
+
+
+
+
+ + +
-
- - -
-
-
- + + +
+
- + +