-
Notifications
You must be signed in to change notification settings - Fork 2
/
bastion.go
208 lines (181 loc) · 5.97 KB
/
bastion.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
package bastion
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strings"
"syscall"
"github.com/go-chi/chi"
chiMiddleware "github.com/go-chi/chi/middleware"
"github.com/markbates/sigtx"
"github.com/rs/zerolog"
"github.com/ifreddyrondon/bastion/middleware"
"github.com/ifreddyrondon/bastion/render"
)
const defaultAddr = ":8080"
// OnShutdown is a function to be implemented when is necessary
// to run something before a shutdown of the server or in graceful shutdown.
type OnShutdown func()
// Bastion offers an "augmented" Router instance.
// It has the minimal necessary to create an API with default handlers and middleware.
// Allows to have commons handlers and middleware between projects with the need for each one to do so.
// Mounted Routers
// It use go-chi router to modularize the applications. Each instance of Bastion, will have the possibility
// of mounting an API router, it will define the routes and middleware of the application with the app logic.
// Without a Bastion you can't do much!
type Bastion struct {
r *chi.Mux
server *http.Server
logger zerolog.Logger
Options
*chi.Mux
}
// New returns a new instance of Bastion and adds some sane, and useful, defaults.
func New(opts ...Opt) *Bastion {
app := &Bastion{
server: &http.Server{},
}
for _, opt := range opts {
opt(app)
}
setDefaultsOpts(&app.Options)
l := getLogger(&app.Options)
app.r = router(app.Options, *l)
app.Mux = chi.NewMux()
app.r.Mount("/", app.Mux)
app.logger = l.With().Str("module", "bastion").Logger()
if app.IsDebug() {
app.logger.Debug().Msg(`Running in "debug" mode. Switch to "production" mode in production.
- using code: bastion.New(bastion.Mode("production"))
- using env: export GO_ENV=production
- using env: export GO_ENVIRONMENT=production
`)
}
return app
}
func router(opts Options, l zerolog.Logger) *chi.Mux {
mux := chi.NewMux()
mux.NotFound(notFound)
mux.MethodNotAllowed(notAllowed)
// logger middleware
if !opts.DisableLoggerMiddleware {
logMiddleware := []middleware.LoggerOpt{
middleware.AttachLogger(l),
}
if !opts.IsDebug() {
logMiddleware = append(
logMiddleware,
middleware.EnableLogReferer(),
middleware.EnableLogUserAgent(),
middleware.EnableLogReqIP(),
)
}
logger := middleware.Logger(logMiddleware...)
mux.Use(logger)
}
// internal error middleware
if !opts.DisableInternalErrorMiddleware {
internalErr := middleware.InternalError(
middleware.InternalErrMsg(errors.New(opts.InternalErrMsg)),
middleware.InternalErrLoggerOutput(opts.LoggerOutput),
)
mux.Use(internalErr)
}
// recovery middleware
if !opts.DisableRecoveryMiddleware {
recovery := middleware.Recovery(middleware.RecoveryLoggerOutput(opts.LoggerOutput))
mux.Use(recovery)
}
if !opts.DisablePingRouter {
mux.Get("/ping", pingHandler)
}
if opts.EnableProfiler {
mux.Mount(opts.ProfilerRoutePrefix, chiMiddleware.Profiler())
}
return mux
}
func notFound(w http.ResponseWriter, r *http.Request) {
render.JSON.NotFound(w, fmt.Errorf("resource %s not found", r.URL.Path))
}
func notAllowed(w http.ResponseWriter, r *http.Request) {
err := fmt.Errorf("method %s not allowed for resource %s", r.Method, r.URL.Path)
render.JSON.MethodNotAllowed(w, err)
}
func printRoutes(mux *chi.Mux, opts Options, l *zerolog.Logger) {
walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
if strings.HasPrefix(route, opts.ProfilerRoutePrefix) {
return nil
}
route = strings.Replace(route, "/*/", "/", -1)
l.Debug().Str("component", "route").Msgf("%s %s", method, route)
return nil
}
if err := chi.Walk(mux, walkFunc); err != nil {
l.Error().Err(err).Msgf("walking through the routes")
}
}
// RegisterOnShutdown registers a function to call on Shutdown.
// This can be used to gracefully shutdown connections that have
// undergone NPN/ALPN protocol upgrade or that have been hijacked.
// This function should start protocol-specific graceful shutdown,
// but should not wait for shutdown to complete.
func (app *Bastion) RegisterOnShutdown(fs ...OnShutdown) {
for _, f := range fs {
app.server.RegisterOnShutdown(f)
}
}
// Serve accepts incoming connections coming from the specified address/port.
// It is a shortcut for http.ListenAndServe(addr, router).
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (app *Bastion) Serve(addr ...string) error {
ctx, cancel := sigtx.WithCancel(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
defer cancel()
go graceful(ctx, app.server, &app.logger)
address := resolveAddress(addr, &app.logger)
app.logger.Info().Msgf("app starting at %v", address)
app.server.Addr = address
app.server.Handler = app.r
printRoutes(app.r, app.Options, &app.logger)
if err := app.server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
app.logger.Info().Str("component", "Serve").Msg("http: Server closed")
return err
}
app.logger.Error().Str("component", "Serve").Err(err).Msg("listenAndServe")
return err
}
return nil
}
func graceful(ctx context.Context, server *http.Server, l *zerolog.Logger) {
<-ctx.Done()
logger := l.With().Str("component", "graceful").Logger()
logger.Info().Msg("preparing for shutdown")
if err := server.Shutdown(ctx); err != nil {
logger.Error().Err(err)
return
}
logger.Info().Msg("gracefully stopped")
}
func resolveAddress(addr []string, l *zerolog.Logger) string {
switch len(addr) {
case 0:
if envAddr := os.Getenv("ADDR"); envAddr != "" {
l.Debug().Msgf(`Environment variable ADDR="%s"`, envAddr)
return envAddr
}
l.Debug().Msg("Environment variable ADDR is undefined. Using addr :8080 by default")
return defaultAddr
case 1:
return addr[0]
default:
panic("too much parameters")
}
}
// NewRouter return a router as a subrouter along a routing path.
// It's very useful to split up a large API as many independent routers and
// compose them as a single service.
func NewRouter() *chi.Mux {
return chi.NewRouter()
}