-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
108 lines (91 loc) · 2.09 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
108
package main
import (
"context"
"os"
"os/signal"
"sync"
"crud_web_service/application"
"crud_web_service/config"
"crud_web_service/controller"
"crud_web_service/model"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
// @title CRUD Web Service
// @description Документация для http сервера приложения
func main() {
appCli := cli.NewApp()
if appCli.Version == "" {
appCli.Version = "version not specified"
}
appCli.Flags = []cli.Flag{
cli.StringFlag{
Name: "config",
Value: "/etc/crud_web_service/config.json",
Usage: "optional config path",
},
}
appCli.Action = func(cliContext *cli.Context) {
cli.ShowVersion(cliContext)
config := config.New(cliContext.String("config"))
m := model.NewFromConfig(config.DB)
if err := m.CheckMigrations(); err != nil {
logrus.WithError(err).Fatal("invalid database condition")
}
shutdown := make(chan int, 16)
wg := sync.WaitGroup{}
appNew := application.New(m, config)
c := controller.New(config, appNew)
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
select {
case <-shutdown:
cancel()
return
}
}
}()
wg.Add(1)
go func() {
c.ServeHTTP(ctx, config.Port)
wg.Done()
}()
gracefulClosing(&wg, shutdown)
}
appCli.Commands = []cli.Command{
{
Name: "migrate",
Usage: "update migrations to the latest stage",
Action: func(cliContext *cli.Context) {
config := config.New(cliContext.GlobalString("config"))
m := model.NewFromConfig(config.DB)
m.Migrate()
},
},
}
if err := appCli.Run(os.Args); err != nil {
panic(err)
}
}
func gracefulClosing(servicesWg *sync.WaitGroup, shutdown chan int) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
logrus.Info("stopping services... (Double enter Ctrl + C to force close)")
close(shutdown)
quit := make(chan struct{})
go func() {
<-sig
<-sig
logrus.Info("services unsafe stopped")
<-quit
}()
go func() {
servicesWg.Wait()
logrus.Info("services gracefully stopped")
<-quit
}()
quit <- struct{}{}
close(quit)
}