/
app.go
101 lines (82 loc) · 1.76 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
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
package app
import (
"strconv"
"github.com/BrobridgeOrg/timer-api-service/app/eventbus"
app "github.com/BrobridgeOrg/timer-api-service/app/interface"
"github.com/nats-io/stan.go"
log "github.com/sirupsen/logrus"
"github.com/soheilhy/cmux"
"github.com/sony/sonyflake"
"github.com/spf13/viper"
)
type App struct {
id uint64
flake *sonyflake.Sonyflake
eventbus *eventbus.EventBus
connectionListener cmux.CMux
grpcServer *GRPCServer
}
func CreateApp() *App {
// Genereate a unique ID for instance
flake := sonyflake.NewSonyflake(sonyflake.Settings{})
id, err := flake.NextID()
if err != nil {
return nil
}
idStr := strconv.FormatUint(id, 16)
return &App{
id: id,
flake: flake,
grpcServer: &GRPCServer{},
eventbus: eventbus.CreateEventBus(
viper.GetString("service.event_server"),
viper.GetString("service.event_cluster_id"),
idStr,
func(conn stan.Conn, err error) {
log.Error("event server was disconnected")
},
),
}
}
func (a *App) Init() error {
log.WithFields(log.Fields{
"a_id": a.id,
}).Info("Starting application")
// Connect to event server
err := a.eventbus.Connect()
if err != nil {
return err
}
return nil
}
func (a *App) Uninit() {
}
func (a *App) Run() error {
port := strconv.Itoa(viper.GetInt("service.port"))
err := a.CreateConnectionListener(":" + port)
if err != nil {
return err
}
// HTTP
go func() {
err := a.InitHTTPServer(":" + port)
if err != nil {
log.Error(err)
}
}()
// gRPC
go func() {
err := a.InitGRPCServer(":" + port)
if err != nil {
log.Error(err)
}
}()
err = a.Serve()
if err != nil {
return err
}
return nil
}
func (a *App) GetEventBus() app.EventBusImpl {
return app.EventBusImpl(a.eventbus)
}