/
router.go
72 lines (59 loc) · 1.53 KB
/
router.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
package router
import (
"context"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/hearchco/hearchco/src/cache"
"github.com/hearchco/hearchco/src/config"
)
// it's okay to store pointer since chi.NewRouter() returns a pointer
type RouterWrapper struct {
mux *chi.Mux
port int
}
func New(lgr zerolog.Logger, conf config.Config, db cache.DB, serveProfiler bool) RouterWrapper {
mux := chi.NewRouter()
setupMiddlewares(mux, lgr, conf.Server.FrontendUrls, serveProfiler)
setupRoutes(mux, db, conf)
return RouterWrapper{mux: mux, port: conf.Server.Port}
}
func (rw RouterWrapper) Start(ctx context.Context) {
// create server
srv := http.Server{
Addr: ":" + strconv.Itoa(rw.port),
Handler: rw.mux,
}
log.Info().
Int("port", rw.port).
Msg("Starting server")
// shut down server gracefully on context cancellation
go func() {
<-ctx.Done()
log.Info().Msg("Shutting down server")
// create a context with timeout of 5 seconds
timeout, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// shutdown gracefully
// after timeout is reached, server will be shut down forcefully
err := srv.Shutdown(timeout)
if err != nil {
log.Error().
Err(err).
Msg("Server shut down failed")
} else {
log.Info().
Msg("Server shut down")
}
}()
// start server
err := srv.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal().
Err(err).
Msg("Failed to start server")
}
}