/
main.go
126 lines (104 loc) · 2.66 KB
/
main.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package app
import (
"context"
"net"
"net/http"
"os"
"os/signal"
"github.com/labstack/echo/v4"
"github.com/reearth/reearth/server/internal/app/config"
"github.com/reearth/reearth/server/internal/usecase/gateway"
"github.com/reearth/reearth/server/internal/usecase/repo"
"github.com/reearth/reearthx/account/accountusecase/accountgateway"
"github.com/reearth/reearthx/account/accountusecase/accountrepo"
"github.com/reearth/reearthx/log"
"golang.org/x/net/http2"
)
func Start(debug bool, version string) {
log.Infof("reearth %s", version)
ctx := context.Background()
// Load config
conf, cerr := config.ReadConfig(debug)
if cerr != nil {
log.Fatalf("failed to load config: %v", cerr)
}
log.Infof("config: %s", conf.Print())
// Init profiler
initProfiler(conf.Profiler, version)
// Init tracer
closer := initTracer(ctx, conf)
defer func() {
if closer != nil {
if err := closer.Close(); err != nil {
log.Errorf("Failed to close tracer: %s\n", err.Error())
}
}
}()
// Init repositories
repos, gateways, acRepos, acGateways := initReposAndGateways(ctx, conf, debug)
// Start web server
NewServer(ctx, &ServerConfig{
Config: conf,
Debug: debug,
Repos: repos,
AccountRepos: acRepos,
Gateways: gateways,
AccountGateways: acGateways,
}).Run()
}
type WebServer struct {
address string
appServer *echo.Echo
}
type ServerConfig struct {
Config *config.Config
Debug bool
Repos *repo.Container
AccountRepos *accountrepo.Container
Gateways *gateway.Container
AccountGateways *accountgateway.Container
}
func NewServer(ctx context.Context, cfg *ServerConfig) *WebServer {
port := cfg.Config.Port
if port == "" {
port = "8080"
}
host := cfg.Config.ServerHost
if host == "" {
if cfg.Debug {
host = "localhost"
} else {
host = "0.0.0.0"
}
}
address := host + ":" + port
w := &WebServer{
address: address,
}
w.appServer = initEcho(ctx, cfg)
return w
}
func (w *WebServer) Run() {
defer log.Infof("Server shutdown")
debugLog := ""
if w.appServer.Debug {
debugLog += " with debug mode"
}
log.Infof("server started%s at http://%s\n", debugLog, w.address)
go func() {
err := w.appServer.StartH2CServer(w.address, &http2.Server{})
log.Fatalf("failed to run server: %v", err)
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
}
func (w *WebServer) Serve(l net.Listener) error {
return w.appServer.Server.Serve(l)
}
func (w *WebServer) ServeHTTP(wr http.ResponseWriter, r *http.Request) {
w.appServer.ServeHTTP(wr, r)
}
func (w *WebServer) Shutdown(ctx context.Context) error {
return w.appServer.Shutdown(ctx)
}