This repository has been archived by the owner on Aug 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
233 lines (186 loc) · 6.17 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/np-inprove/server/internal/auth"
"github.com/np-inprove/server/internal/config"
"github.com/np-inprove/server/internal/ent"
"github.com/np-inprove/server/internal/group"
"github.com/np-inprove/server/internal/institution"
"github.com/np-inprove/server/internal/logger"
"github.com/np-inprove/server/internal/seed"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/jwtauth/v5"
"github.com/go-chi/render"
"github.com/lestrrat-go/jwx/v2/jwk"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
func main() {
cfg, err := config.New()
if err != nil {
log.Fatalf("failed to create app config: %v", err)
}
var appLogger logger.AppLogger
if cfg.AppProduction() {
appLogger, err = logger.NewZapProduction()
} else {
appLogger = logger.NewCharm()
}
if err != nil {
log.Fatalf("failed to create app logger: %v", err)
}
appLogger.Info("initializing server: hello, world!")
appLogger.Info("opening connection",
logger.String("area", "database"),
logger.String("driver_name", cfg.DatabaseDriverName()),
)
client, err := ent.Open(cfg.DatabaseDriverName(), cfg.DatabaseDataSourceName())
if err != nil {
appLogger.Fatal("failed opening connection",
logger.String("err", err.Error()),
logger.String("area", "database"),
)
}
defer func(client *ent.Client) {
_ = client.Close()
}(client)
if cfg.DatabaseAutoMigration() {
appLogger.Info("running auto migration",
logger.String("area", "database"),
logger.String("driver_name", cfg.DatabaseDriverName()),
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := client.Schema.Create(ctx); err != nil {
appLogger.Fatal("failed creating schema resources",
logger.String("err", err.Error()),
logger.String("area", "database"),
logger.String("driver_name", cfg.DatabaseDriverName()),
)
}
}
privateKey, err := jwk.ParseKey([]byte(cfg.AppJWK()))
if err != nil {
appLogger.Fatal("failed to parse jwk", logger.String("err", err.Error()))
}
publicKey, err := privateKey.PublicKey()
if err != nil {
appLogger.Warn("failed to get jwk public key, if the jwt algorithm requires a public key, it will not work", logger.String("err", err.Error()))
}
appLogger.Info("seeding database",
logger.String("area", "database"),
logger.String("driver_name", cfg.DatabaseDriverName()),
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = seed.Exec(ctx, appLogger, cfg, client)
if err != nil {
appLogger.Fatal("failed to seed data", logger.String("err", err.Error()))
}
appLogger.Info("creating http server",
logger.String("area", "http"),
)
r := chi.NewRouter()
loggerMiddleware := logger.NewMiddleware(appLogger)
tokenAuth := jwtauth.New(privateKey.Algorithm().String(), privateKey, publicKey)
r.Use(cors.Handler(cors.Options{
AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))
r.Use(middleware.RequestID)
r.Use(middleware.Recoverer)
r.Use(middleware.URLFormat)
r.Use(loggerMiddleware.Request)
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
render.DefaultResponder(w, r, render.M{"ok": true})
})
server := http.Server{Addr: cfg.HTTPAddr(), Handler: r}
appLogger.Info("registering services",
logger.String("area", "auth"),
)
authRepo := auth.NewEntRepository(client)
authUseCase := auth.NewUseCase(authRepo, cfg, publicKey, privateKey)
if err != nil {
appLogger.Fatal("failed to initialize auth use case",
logger.String("err", err.Error()),
)
}
authHandler := auth.NewHTTPHandler(authUseCase, cfg, tokenAuth)
r.Mount("/auth", authHandler)
appLogger.Info("registering services",
logger.String("area", "institution"),
)
instRepo := institution.NewEntRepository(appLogger, client)
instUseCase := institution.NewUseCase(instRepo)
instHandler := institution.NewHTTPHandler(instUseCase, cfg, tokenAuth)
r.Mount("/institutions", instHandler)
appLogger.Info("registering services",
logger.String("area", "group"),
)
groupRepo := group.NewEntRepository(appLogger, client)
groupService := group.NewUseCase(groupRepo)
groupHandler := group.NewHTTPHandler(groupService, cfg, tokenAuth)
r.Mount("/groups", groupHandler)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGTERM, syscall.SIGINT)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
appLogger.Info("ready to handle requests",
logger.String("area", "http"),
logger.String("addr", cfg.HTTPAddr()),
)
err = server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
appLogger.Fatal("failed to listen",
logger.String("err", err.Error()),
logger.String("area", "http"),
logger.String("addr", cfg.HTTPAddr()),
)
}
wg.Done()
}()
go func() {
i := <-interrupt
appLogger.Info("interrupt detected and shutting down gracefully",
logger.String("signal", i.String()),
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
appLogger.Info("shutting down http server", logger.String("area", "http"))
err = server.Shutdown(ctx)
if err != nil {
appLogger.Fatal("failed to shut down http server gracefully",
logger.String("err", err.Error()),
logger.String("area", "http"),
)
}
appLogger.Info("successfully shut down http server", logger.String("area", "http"))
appLogger.Info("closing connection with database", logger.String("area", "database"))
err = client.Close()
if err != nil {
appLogger.Fatal("failed to close database connection",
logger.String("err", err.Error()),
logger.String("area", "database"),
)
}
appLogger.Info("closed connection with database",
logger.String("area", "database"),
)
}()
wg.Wait()
appLogger.Info("completed graceful shutdown, bye!")
}