-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.go
112 lines (89 loc) · 2.33 KB
/
provider.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
109
110
111
112
package giris
import (
"context"
"fmt"
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/recover"
"github.com/mylxsw/asteria/log"
"github.com/mylxsw/glacier/infra"
"github.com/mylxsw/graceful"
)
type Option func(resolver infra.Resolver, irisApp *iris.Application)
type serviceProvider struct {
listenerBuilder infra.ListenerBuilder
options []Option
}
func Provider(listenerBuilder infra.ListenerBuilder, options ...Option) infra.DaemonProvider {
return serviceProvider{
listenerBuilder: listenerBuilder,
options: options,
}
}
func (p serviceProvider) Register(app infra.Binder) {
app.MustSingletonOverride(func() *iris.Application {
app := iris.New()
app.Use(recover.New())
app.Configure(iris.WithoutStartupLog)
app.Logger().Install(logger{})
return app
})
}
func (p serviceProvider) Boot(app infra.Resolver) {
app.MustResolve(func(irisApp *iris.Application) {
for _, opt := range p.options {
opt(app, irisApp)
}
})
}
func (p serviceProvider) Daemon(ctx context.Context, app infra.Resolver) {
app.MustResolve(func(gf graceful.Graceful, irisApp *iris.Application) {
listener, err := p.listenerBuilder.Build(app)
if err != nil {
panic(err)
}
gf.AddShutdownHandler(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if log.DebugEnabled() {
log.Debugf("prepare to shutdown http server...")
}
if err := irisApp.Shutdown(ctx); err != nil {
log.Errorf("shutdown http server failed: %s", err)
}
if log.WarningEnabled() {
log.Warning("http server has been shutdown")
}
})
if log.DebugEnabled() {
log.Debugf("http server started, listening on %s", listener.Addr())
}
if err := irisApp.Run(iris.Listener(listener)); err != nil {
if log.DebugEnabled() {
log.Debugf("http server stopped: %v", err)
}
if err != iris.ErrServerClosed {
gf.Shutdown()
}
}
})
}
type logger struct{}
func (l logger) Print(i ...interface{}) {
log.Debug(i...)
}
func (l logger) Println(i ...interface{}) {
log.Debugf(fmt.Sprintf("%v", i[0]), i[1:]...)
}
func (l logger) Error(i ...interface{}) {
log.Error(i...)
}
func (l logger) Warn(i ...interface{}) {
log.Warning(i...)
}
func (l logger) Info(i ...interface{}) {
log.Info(i...)
}
func (l logger) Debug(i ...interface{}) {
log.Debug(i...)
}