-
Notifications
You must be signed in to change notification settings - Fork 2
/
application.go
91 lines (76 loc) · 1.7 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package hermes
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/lab259/go-rscsrv"
)
type ApplicationConfig struct {
Name string
ServiceStarter rscsrv.ServiceStarter
HTTP FasthttpServiceConfiguration
}
type Application struct {
serviceState
fasthttpService FasthttpService
Configuration ApplicationConfig
done chan bool
signals chan os.Signal
}
func NewApplication(config ApplicationConfig, router Router) *Application {
app := &Application{
Configuration: config,
}
if config.Name != "" {
app.fasthttpService.Server.Name = fmt.Sprintf("fasthttp/%s", config.Name)
}
app.fasthttpService.Server.Handler = router.Handler()
app.done = make(chan bool, 1)
app.signals = make(chan os.Signal, 1)
return app
}
func (app *Application) Name() string {
if app.Configuration.Name == "" {
return "Application"
}
return app.Configuration.Name
}
func (app *Application) Restart() error {
if err := app.Stop(); err != nil {
return err
}
return app.Start()
}
func (app *Application) Start() error {
err := app.fasthttpService.ApplyConfiguration(app.Configuration.HTTP)
if err != nil {
return err
}
go func() {
signal.Notify(app.signals, syscall.SIGINT, syscall.SIGTERM)
if _, ok := <-app.signals; ok {
app.Stop()
}
}()
app.setRunning(true)
if err := app.fasthttpService.Start(); err != nil {
return err
}
<-app.done
return nil
}
func (app *Application) Stop() error {
if app.isRunning() {
defer func() {
if app.Configuration.ServiceStarter != nil {
app.Configuration.ServiceStarter.Stop(true)
}
signal.Stop(app.signals)
app.done <- true
app.setRunning(false)
}()
return app.fasthttpService.Stop()
}
return nil
}