-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (66 loc) · 1.65 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
package main
import (
"log"
"net/http"
"strconv"
"github.com/jinzhu/gorm"
"github.com/labstack/echo/v4"
"img-hosting/config"
"img-hosting/controller"
"img-hosting/db"
"img-hosting/middleware"
"img-hosting/model"
"img-hosting/router"
"img-hosting/utils"
)
func initMiddlewares(e *echo.Echo, conf *config.Config) {
middleware.Init(e, conf)
}
func initRoutes(e *echo.Echo, conf *config.Config, db *gorm.DB) {
router.Init(e, conf, db)
}
func initDB(db *gorm.DB) {
db.AutoMigrate(&model.Img{}, &model.User{}, &model.Log{})
}
func main() {
// 初始化配置
conf, err := config.Initialize()
if err != nil {
log.Fatal(err)
}
orm := db.ORM{Name: "mysql"}
dbConfig, ok := conf.Databases["mysql"]
if !ok {
log.Fatal("Can not load configuration of MySQL")
}
connectionURL := dbConfig.Username + ":" + dbConfig.Password + "@" + "tcp(" + dbConfig.Host + ":" + strconv.Itoa(dbConfig.Port) + ")/" + dbConfig.DBName + "?charset=utf8&parseTime=True&loc=Local"
orm.Open(connectionURL)
defer orm.Close()
initDB(orm.DB)
e := echo.New()
// 全局错误处理
e.HTTPErrorHandler = func(err error, c echo.Context) {
c.JSON(http.StatusOK, controller.BaseResponseJSON{
Success: false,
Code: controller.STATUS_ERROR,
Message: err.Error(),
})
}
// 初始化中间件
initMiddlewares(e, &conf)
// 初始化路由
initRoutes(e, &conf, orm.DB)
// 运行服务
if conf.Server.Port == 80 {
e.Logger.Fatal(e.Start(conf.Server.Host))
} else {
e.Logger.Fatal(e.Start(conf.Server.Host + ":" + strconv.Itoa(conf.Server.Port)))
}
}
func init() {
// 初始化目录
err := utils.MkdirIFNotExist("public")
if err != nil {
log.Fatal(err)
}
}