/
application.go
68 lines (58 loc) · 1.15 KB
/
application.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
package common
import (
"context"
"fmt"
"github.com/jessevdk/go-flags"
"go.uber.org/fx"
"os"
)
type Application struct {
ctx context.Context
cancel context.CancelFunc
fxApp *fx.App
options []fx.Option
}
func NewApplication(providers ...interface{}) *Application {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
app := &Application{
options: []fx.Option{
fx.NopLogger,
},
ctx: ctx,
cancel: cancel,
}
for _, provider := range providers {
switch p := provider.(type) {
case fx.Option:
app.options = append(app.options, p)
default:
app.options = append(app.options, fx.Provide(p))
}
}
return app
}
func (a *Application) Run(invoker interface{}) {
var args Arguments
_, err := flags.Parse(&args)
if err != nil {
panic(err)
}
a.options = append(
a.options,
fx.Provide(func() context.Context {
return a.ctx
}),
fx.Provide(func() Arguments {
return args
}),
fx.Invoke(invoker),
)
a.fxApp = fx.New(a.options...)
startCtx, cancel := context.WithTimeout(a.ctx, fx.DefaultTimeout)
defer cancel()
if err = a.fxApp.Start(startCtx); err != nil {
fmt.Println(err)
os.Exit(1)
}
}