-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (61 loc) · 1.82 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
package main
import (
"net/http"
"strconv"
"allandeng.cn/allandeng/go-blog/metrics"
_ "github.com/jinzhu/gorm/dialects/mysql"
"allandeng.cn/allandeng/go-blog/config"
dao "allandeng.cn/allandeng/go-blog/repository"
"allandeng.cn/allandeng/go-blog/router"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/op/go-logging"
)
var log *logging.Logger
func init() {
log = config.Logger
}
func main() {
//创建 promethues metrics
metrics.Init()
//创建并注册路由
muxRouter := mux.NewRouter()
router.Register(muxRouter)
//连接到数据库并初始化
dbConf := config.GlobalConfig.Mysql
db, err := GetDbConnect(dbConf.User, dbConf.Pwd, dbConf.Host, dbConf.Dbname)
if err != nil {
log.Panicf("Error : can't connent to database ; %s", err)
}
InitDaoAndTable(db)
srv := "0.0.0.0:" + strconv.Itoa(int(config.GlobalConfig.WebServer.Port))
log.Infof("Start server on %s", srv)
err = http.ListenAndServe(srv, muxRouter) // 设置监听的端口
if err != nil {
log.Panicf("Panic create server failed : ", err)
}
}
//连接数据库的函数
func GetDbConnect(user string, password string, host string, dbname string) (*gorm.DB, error) {
dbString := user + ":" + password + "@tcp(" + host + ")/" + dbname + "?charset=utf8&parseTime=True"
log.Infof("Connect database string : %s", dbString)
db, err := gorm.Open("mysql", dbString)
if err != nil {
return nil, err
}
db.SingularTable(true)
return db, nil
}
//初始化repository和对应的表
func InitDaoAndTable(db *gorm.DB) {
dao.InitBlogRepository(db)
dao.InitCommentRepository(db)
dao.InitTagRepository(db)
dao.InitTypeRepository(db)
dao.InitUserRepository(db)
dao.GetBlogRepository().InitTable()
dao.GetCommentRepository().InitTable()
dao.GetTagRepository().InitTable()
dao.GetTypeRepository().InitTable()
dao.GetUserRepository().InitTable()
}