feat: speedtest 网速测试服务(Go+Gin+SQLite,延迟/下载/上传 + 排行榜)

This commit is contained in:
dsh
2026-08-17 09:32:05 -04:00
commit 3b48eea5d1
15 files changed
+1855

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
package db
import (
"fmt"
"os"
"path/filepath"
"speedtest/config"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// InitDB initializes the database connection and performs auto-migration.
func InitDB(cfg config.DatabaseConfig) (*gorm.DB, error) {
var dialector gorm.Dialector
switch cfg.Driver {
case "sqlite":
dsn := cfg.DSN
// 如果 DSN 是默认相对路径,则基于 base dir 解析
if dsn == config.DefaultDSNWin || dsn == config.DefaultDSNLinux {
dsn = filepath.Join(config.LinuxBaseDir, "speedtest.db")
}
// 确保 SQLite 父目录存在
dir := filepath.Dir(dsn)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("创建数据库目录失败 %s: %w", dir, err)
}
dialector = sqlite.Open(dsn)
default:
return nil, fmt.Errorf("不支持的数据库驱动: %s", cfg.Driver)
}
database, err := gorm.Open(dialector, &gorm.Config{
Logger: logger.Default.LogMode(logger.Warn),
})
if err != nil {
return nil, fmt.Errorf("连接数据库失败: %w", err)
}
// Auto-migrate all models
if err := database.AutoMigrate(&SpeedTestResult{}); err != nil {
return nil, fmt.Errorf("数据库迁移失败: %w", err)
}
return database, nil
}
+14
View File
@@ -0,0 +1,14 @@
package db
import "time"
// SpeedTestResult 一次完整的测速结果记录
type SpeedTestResult struct {
ID uint `gorm:"primaryKey" json:"id"`
ClientIP string `gorm:"size:64;index" json:"client_ip"`
LatencyMs float64 `json:"latency_ms"` // 延迟(毫秒,取中位数)
JitterMs float64 `json:"jitter_ms"` // 抖动(毫秒,平均绝对偏差)
DownloadMbps float64 `json:"download_mbps"` // 下载速度(Mbps
UploadMbps float64 `json:"upload_mbps"` // 上传速度(Mbps
CreatedAt time.Time `gorm:"index" json:"created_at"`
}