-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
129 lines (101 loc) · 3.55 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
package main
import (
"compress/flate"
"context"
"fmt"
"net/http"
"os"
"os/signal"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
newrelic "github.com/newrelic/go-agent"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
"github.com/AndersonQ/go-skeleton/config"
"github.com/AndersonQ/go-skeleton/handlers"
"github.com/AndersonQ/go-skeleton/middlewares"
)
func main() {
// catch the signals as soon as possible
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt) // a.k.a ctrl+C
// when closed the program should exit
idleConnsClosed := make(chan bool)
cfg, err := config.Parse()
if err != nil {
panic("could not parse environment variables: " + err.Error())
}
logger := cfg.Logger()
newrelicApp, err := initNewrelic(cfg, logger)
if err != nil {
logger.Warn().Err(err).Msg("could init newrelic agent")
}
router := initRouter(cfg, newrelicApp, logger)
server := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.ServerPort),
Handler: router,
IdleTimeout: cfg.IdleTimeout,
WriteTimeout: cfg.WriteTimeout,
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
}
// handle graceful shutdown in another goroutine
go gracefullShutdown(signalChan, idleConnsClosed, cfg, server, newrelicApp, logger)
logger.Info().Msgf("staring server on :%d", cfg.ServerPort)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
logger.Err(err).Msg("HTTP server error")
} else {
logger.Info().Msg("shutting server down...")
}
<-idleConnsClosed
}
func initRouter(cfg config.Config, newrelicApp newrelic.Application, logger zerolog.Logger) *chi.Mux {
router := chi.NewRouter()
router.Use(middlewares.RequestIDHandler)
router.Use(hlog.NewHandler(logger))
router.Use(middleware.StripSlashes)
router.Use(middleware.Compress(flate.BestSpeed))
router.Use(middlewares.JsonResponse)
router.Use(middlewares.RequestLogWrapper)
router.Use(middlewares.TimeoutWrapper(cfg.RequestTimeout))
router.Get(newrelic.WrapHandleFunc(newrelicApp, "/live", handlers.NewLivenessHandler()))
router.Get(newrelic.WrapHandleFunc(newrelicApp, "/ready", handlers.NewReadinessHandler()))
router.Get(newrelic.WrapHandleFunc(newrelicApp, "/slow", handlers.NewSlowHandler(
cfg.RequestTimeout+time.Millisecond*5)))
return router
}
func initNewrelic(cfg config.Config, logger zerolog.Logger) (newrelic.Application, error) {
ncfg := newrelic.NewConfig(cfg.AppName, cfg.NewRelicKey)
// Disable communication with newrelic, see https://github.com/newrelic/go-agent/blob/master/config.go#L27
if len(cfg.NewRelicKey) == 0 {
ncfg.Enabled = false
logger.Warn().Msg("Disabling NewRelic as license key is empty")
}
app, err := newrelic.NewApplication(ncfg)
return app, err
}
func gracefullShutdown(
signalChan chan os.Signal,
idleConnsClosed chan bool,
cfg config.Config,
server *http.Server,
newrelicApp newrelic.Application,
logger zerolog.Logger) {
sig := <-signalChan
logger.Info().Msgf("received signal: %q, starting graceful shutdown...", sig.String())
ctx, done := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer done() // avoid a context leak
if err := server.Shutdown(ctx); err != nil {
logger.Error().Err(err).Msg("error during gracefully shutdown")
}
deadline, _ := ctx.Deadline()
if newrelicApp != nil {
logger.Info().Msg("shunting down Newrelic")
newrelicApp.Shutdown(deadline.Sub(time.Now()))
} else {
logger.Info().Msg("newrelic not initialised, nothing to shutdown")
}
logger.Info().Msg("Gracefully shutdown finished")
close(idleConnsClosed)
}