69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
"level_go/internal/service"
|
|
"level_go/pkg/config"
|
|
)
|
|
|
|
func main() {
|
|
// 1. 加载配置
|
|
config.InitConfig()
|
|
dbConf := config.AppConfig.Database
|
|
|
|
// 2. 连接数据库
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
|
|
dbConf.User, dbConf.Password, dbConf.Host, dbConf.Port, dbConf.Dbname, dbConf.Charset)
|
|
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
panic("数据库连接失败: " + err.Error())
|
|
}
|
|
|
|
// 3. 注入 Service
|
|
stockSvc := &service.StockService{DB: db}
|
|
|
|
// 4. 路由设置
|
|
r := gin.Default()
|
|
|
|
// 跨域中间件
|
|
r.Use(func(c *gin.Context) {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
c.Next()
|
|
})
|
|
|
|
api := r.Group("/api/v1")
|
|
{
|
|
api.GET("/stock/analyze", func(c *gin.Context) {
|
|
start := c.Query("start_date")
|
|
end := c.Query("end_date")
|
|
|
|
if start == "" || end == "" {
|
|
c.JSON(400, gin.H{"error": "参数缺失"})
|
|
return
|
|
}
|
|
|
|
data, err := stockSvc.AnalyzePerformance(start, end)
|
|
if err != nil {
|
|
c.JSON(500, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(200, data)
|
|
})
|
|
}
|
|
|
|
// 5. 启动
|
|
port := fmt.Sprintf(":%d", config.AppConfig.Server.Port)
|
|
fmt.Printf("服务已启动,监听端口 %s\n", port)
|
|
r.Run(port)
|
|
}
|