-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
96 lines (76 loc) · 1.71 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
package main
import (
"net/http"
"os"
"github.com/ecojuntak/gorb/middlewares"
"github.com/jinzhu/gorm"
"github.com/sirupsen/logrus"
"github.com/gorilla/handlers"
"github.com/ecojuntak/gorb/database"
"github.com/urfave/cli"
"github.com/spf13/viper"
)
func onError(err error, failedMessage string) {
if err != nil {
logrus.Errorln(failedMessage)
logrus.Errorln(err)
}
}
func loadConfig() (err error) {
viper.SetConfigName("config")
viper.AddConfigPath(".")
err = viper.ReadInConfig()
return err
}
func runServer(db *gorm.DB) {
r := LoadRouter(db)
corsOption := middlewares.CorsMiddleware()
logrus.Infoln("Server run on " + getAddress())
http.ListenAndServe(getAddress(), handlers.CORS(corsOption[0], corsOption[1], corsOption[2])(r))
}
func main() {
err := loadConfig()
if err != nil {
logrus.Errorln(err)
}
db, err := database.InitDatabase()
err = db.DB().Ping()
if err != nil {
logrus.Errorln(err)
}
defer db.Close()
cliApp := cli.NewApp()
cliApp.Name = "GORB"
cliApp.Version = "1.0.0"
cliApp.Commands = []cli.Command{
{
Name: "migrate",
Description: "Run database migration",
Action: func(c *cli.Context) error {
err = database.Migrate(db)
onError(err, "Failed to migrate database schema")
return err
},
},
{
Name: "seed",
Description: "Run database seeder",
Action: func(c *cli.Context) error {
err = database.RunSeeder(db)
onError(err, "Failed to generate fake data")
return err
},
},
{
Name: "start",
Description: "Start REST API Server",
Action: func(c *cli.Context) error {
runServer(db)
return nil
},
},
}
if err := cliApp.Run(os.Args); err != nil {
logrus.Fatalln(err)
}
}