-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
61 lines (51 loc) · 1.11 KB
/
app.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
package app
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/brilliant-monkey/go-app/config"
"golang.org/x/sync/errgroup"
)
type App struct {
cancel context.CancelFunc
errGroup *errgroup.Group
errGroupCtx context.Context
}
func waitForExit(cancel context.CancelFunc) {
exit := make(chan os.Signal, 1)
signal.Notify(exit, os.Interrupt, syscall.SIGTERM)
<-exit
log.Println("Terminating application...")
cancel()
}
func NewApp() *App {
ctx, cancel := context.WithCancel(context.Background())
g, gCtx := errgroup.WithContext(ctx)
return &App{
cancel: cancel,
errGroup: g,
errGroupCtx: gCtx,
}
}
func (app *App) LoadConfig(pathEnv string, out interface{}) {
if err := config.Load(pathEnv, out); err != nil {
panic(err)
}
}
func (app *App) Go(process func() error) {
app.errGroup.Go(process)
}
func (app *App) Start(stopCallback func() error) (err error) {
go waitForExit(app.cancel)
app.errGroup.Go(func() error {
<-app.errGroupCtx.Done()
return stopCallback()
})
err = app.errGroup.Wait()
if err != nil {
log.Printf("exit reason: %s", err.Error())
}
return
}