-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (92 loc) · 2.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
"strings"
"github.com/gofiber/fiber/v2"
fiberLogger "github.com/gofiber/fiber/v2/middleware/logger"
"github.com/sirupsen/logrus"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"github.com/Kirisakiii/neko-micro-blog-backend/config"
"github.com/Kirisakiii/neko-micro-blog-backend/controllers"
"github.com/Kirisakiii/neko-micro-blog-backend/loggers"
"github.com/Kirisakiii/neko-micro-blog-backend/models"
"github.com/Kirisakiii/neko-micro-blog-backend/services"
"github.com/Kirisakiii/neko-micro-blog-backend/stores"
)
var (
logger *logrus.Logger
cfg *config.Config
db *gorm.DB
controllerFactory *controllers.Factory
)
func init() {
// logger
logger = loggers.NewLogger()
logger.Infoln("正在执行程序初始化...")
var err error
// 加载配置文件
cfg, err = config.NewConfig()
if err != nil {
logger.Panicln(err.Error())
}
// 设置日志等级
var (
logLevel logrus.Level
logMode gormLogger.LogLevel
)
switch cfg.Env.Type {
case "development":
logLevel = logrus.DebugLevel
logMode = gormLogger.Error
case "production":
logLevel = logrus.InfoLevel
logMode = gormLogger.Silent
default:
logLevel = logrus.InfoLevel
logMode = gormLogger.Silent
}
// 设置logrus日志等级
logger.SetLevel(logLevel)
logger.Debugln("日志记录等级设定为:", strings.ToUpper(logLevel.String()))
// 连接数据库
logger.Debugln("尝试连接至数据库...")
db, err = gorm.Open(
postgres.Open(fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s",
cfg.Database.User,
cfg.Database.Password,
cfg.Database.Host,
cfg.Database.Port,
cfg.Database.DBName,
)),
&gorm.Config{
Logger: gormLogger.Default.LogMode(logMode),
},
)
if err != nil {
logger.Panicln(err.Error())
}
logger.Debugln("数据库连接成功")
// 迁移模型
logger.Debugln("正在迁移数据表模型...")
models.Migrate(db)
// 建立控制器层工厂
controllerFactory = controllers.NewFactory(
services.NewFactory(
stores.NewFactory(db),
),
)
}
func main() {
app := fiber.New()
app.Use(fiberLogger.New(fiberLogger.Config{
Format: "[${time}][${latency}][${status}][${method}] ${path}\n",
}))
// User 路由
userController := controllerFactory.NewUserController()
app.Get("/api/user/profile", userController.NewProfileHandler()) // 查询用户信息
app.Post("/api/user/register", userController.NewRegisterHandler()) // 用户注册
app.Listen(fmt.Sprintf(":%d", cfg.Server.Port))
}