-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
63 lines (49 loc) · 1.62 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
package main
import (
"github.com/jmoiron/sqlx"
"github.com/panjf2000/gnet/v2"
"github.com/rs/zerolog/log"
"hc/api/config"
"hc/api/packet"
"net/http"
_ "net/http/pprof"
)
type App struct {
PacketResolver packet.Resolver
Config config.Reader
GameServer gnet.EventHandler
DB *sqlx.DB
}
func (a *App) Run(addr string) error {
routes := CollectRoutes()
a.PacketResolver.SetPackets(routes)
log.Info().Msgf("Registered %d packets", len(routes))
a.checkDatabase()
a.startProfilerIfEnabled()
log.Info().Msgf("Starting %s on address %s", a.Config.GetString("app.name"), addr)
if err := gnet.Run(a.GameServer, addr, gnet.WithMulticore(true)); err != nil {
log.Error().Msgf("unable to execute game server: %s", err.Error())
}
return nil
}
// startProfilerIfEnabled starts the pprof profiler if enabled. It's encouraged to keep the profiler active on production
// environments in order to locate potential bottlenecks.
func (a *App) startProfilerIfEnabled() {
profilerEnabled := a.Config.GetBool("app.profiler_enabled")
if !profilerEnabled {
log.Warn().Msg("Profiler is disabled! Enabling it is recommended. Enable it in config/app.yaml or set APP_PROFILER_ENABLED=true")
return
}
log.Info().Msg("Profiler (pprof) enabled")
go func() {
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Error().Msgf("Profiler stopped! Err: %s", err.Error())
}
}()
}
func (a *App) checkDatabase() {
if err := a.DB.Ping(); err != nil {
log.Fatal().Msgf("Server stopped! Database connection is not available, err: %s", err.Error())
}
log.Info().Msg("Database connection is established")
}