Files
hldrCenter/server/main.go

77 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/JACKYMYPERSON/hldrCenter/config"
"github.com/JACKYMYPERSON/hldrCenter/init/database/cache"
"github.com/JACKYMYPERSON/hldrCenter/middleware/cors"
"github.com/JACKYMYPERSON/hldrCenter/router"
)
func main() {
// 目标开发环境go run找项目根目录的 config生产环境打包后找可执行文件同级的 config
var configPath string
// 1. 先获取当前程序的路径(开发时是临时路径,生产时是打包后的路径)
exePath, err := os.Executable()
if err != nil {
fmt.Printf("获取程序路径失败:%v\n", err)
return
}
exeDir := filepath.Dir(exePath)
// 2. 开发环境兼容:判断是否在 GoLand 的临时目录(或项目根目录)
// 逻辑:如果 exeDir 包含 "tmp"(临时目录特征),则去上级目录找项目根的 config
// 可根据你的项目结构调整判断逻辑(比如项目名包含 "myproject",也可以判断 strings.Contains(exeDir, "myproject")
if strings.Contains(strings.ToLower(exeDir), "tmp") {
// 开发环境:从临时目录向上回溯,找到项目根目录(根据实际项目层级调整 ../ 的数量)
// 示例:临时目录 → 项目根目录(假设临时目录在项目根下的 tmp 子目录需回溯1级
projectRoot := filepath.Join(exeDir, "..") // 若回溯不够,可改成 "../..",直到找到项目根
configPath = filepath.Join(projectRoot, "config", "config.yaml")
// 验证如果没找到再尝试用当前工作目录go run 的工作目录默认是项目根)
if _, err := os.Stat(configPath); err != nil {
configPath = filepath.Join(".", "config", "config.yaml")
}
} else {
// 生产环境(打包后):用可执行文件同级的 config 文件夹
configPath = filepath.Join(exeDir, "config", "config.yaml")
}
// 3. 验证路径是否存在(可选,方便调试)
if _, err := os.Stat(configPath); err != nil {
fmt.Printf("配置文件不存在:%s\n", configPath)
return
}
cfg, err := config.LoadConfig(configPath)
if err != nil {
fmt.Printf("加载配置失败:%v\n", err)
return
}
cache.InitCache()
defer func() {
err := cache.CloseCache()
if err != nil {
return
}
}()
// 设置路由
r := router.SetupRouter(cfg)
// 应用跨域中间件
r.Use(cors.CorsMiddleware(&cfg.Server))
// 启动服务
addr := fmt.Sprintf(":%s", cfg.Server.Port)
fmt.Printf("后端服务启动成功地址http://localhost%s\n", addr)
if err := r.Run(addr); err != nil {
fmt.Printf("服务启动失败:%v\n", err)
}
}