package main import ( "license-admin/database" "license-admin/handlers" "license-admin/middleware" "license-admin/models" "log" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // seedData 初始化种子数据 // 在数据库为空时,自动插入一条测试数据 func seedData(db *gorm.DB) error { var count int64 // 检查数据库中是否已有数据 if err := db.Model(&models.License{}).Count(&count).Error; err != nil { return err } // 如果数据库为空,插入测试数据 if count == 0 { testLicense := models.License{ Key: "TEST-KEY-123456", BoundDevices: "[]", // 空数组 MaxDevices: 2, } if err := db.Create(&testLicense).Error; err != nil { return err } log.Println("已插入测试数据: Key=TEST-KEY-123456, MaxDevices=2") } return nil } func main() { // 初始化数据库 if err := database.InitDB(); err != nil { log.Fatalf("初始化数据库失败: %v", err) } // 初始化种子数据(如果数据库为空) if err := seedData(database.DB); err != nil { log.Fatalf("初始化种子数据失败: %v", err) } // 创建 Gin 路由 r := gin.Default() // 添加 CORS 中间件(Chrome 插件可能需要) r.Use(func(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(204) return } c.Next() }) // 静态文件服务(前端页面) r.Static("/web", "./web") r.GET("/", func(c *gin.Context) { c.Redirect(302, "/web/login.html") }) // 健康检查接口 r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{ "status": "ok", }) }) // API 路由组 api := r.Group("/api") { // 公开接口(不需要认证) api.POST("/verify", handlers.VerifyLicense(database.DB)) // License 验证接口(Chrome插件使用) api.POST("/login", handlers.Login()) // 登录接口 // 需要认证的管理接口 api.Use(middleware.AuthMiddleware()) { // License 管理接口(CRUD) licenses := api.Group("/licenses") { licenses.POST("", handlers.CreateLicense(database.DB)) // 创建 License licenses.POST("/batch", handlers.BatchCreateLicense(database.DB)) // 批量创建 License licenses.DELETE("/batch", handlers.BatchDeleteLicense(database.DB)) // 批量删除 License licenses.GET("", handlers.GetLicenseList(database.DB)) // 获取 License 列表 licenses.GET("/:id", handlers.GetLicense(database.DB)) // 获取单个 License licenses.PUT("/:id", handlers.UpdateLicense(database.DB)) // 更新 License licenses.DELETE("/:id", handlers.DeleteLicense(database.DB)) // 删除 License } } } // 启动服务器 log.Println("License 验证服务启动在 :8080") if err := r.Run(":8080"); err != nil { log.Fatalf("启动服务器失败: %v", err) } }