-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (77 loc) · 2.01 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
package main
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"strconv"
"time"
dbmodels "github.com/Team-IF/TeamWork_Backend/models/db"
v1 "github.com/Team-IF/TeamWork_Backend/routes/v1"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/BurntSushi/toml"
"github.com/Team-IF/TeamWork_Backend/middlewares"
"github.com/Team-IF/TeamWork_Backend/models"
"github.com/Team-IF/TeamWork_Backend/utils"
"github.com/gin-gonic/gin"
)
func main() {
etcInit()
applyConfig()
initDB()
startServer()
}
func etcInit() {
rand.Seed(time.Now().Unix())
}
func applyConfig() {
rawConfig, err := ioutil.ReadFile("config.toml")
if err != nil {
log.Fatalln("Failed to load config.")
}
var config models.Config
if _, err := toml.Decode(string(rawConfig), &config); err != nil {
log.Println(err.Error())
log.Fatalln("Failed to parsing config.")
}
utils.SetConfig(&config)
}
func startServer() {
config := utils.GetConfig().Server
if config.Debug {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
r := gin.Default()
r.Use(middlewares.Cors())
version1 := r.Group("/v1")
v1.InitRoutes(version1)
r.Run(":" + strconv.Itoa(config.Port))
}
func initDB() {
config := utils.GetConfig()
log.Println("Initializing Database...")
var db *gorm.DB
var err error
if config.Server.UseTestDB {
dbConfig := config.TestDB
db, err = gorm.Open(sqlite.Open(dbConfig.Path), &gorm.Config{})
} else {
dbConfig := config.DB
connectionInfo := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", dbConfig.Username, dbConfig.Password, dbConfig.Hostname, dbConfig.Port, dbConfig.DBName)
db, err = gorm.Open(mysql.Open(connectionInfo), &gorm.Config{})
}
if err != nil {
log.Fatalln("Failed to open database.")
}
utils.SetDB(db)
log.Print("Successfully Connected To Database")
var models = []interface{}{&dbmodels.User{}}
if err := db.AutoMigrate(models...); err != nil {
log.Fatalln("Failed to perform AutoMigrate.")
}
log.Print("Successfully performed AutoMigrate")
}