-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
383 lines (333 loc) · 9.8 KB
/
app.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package api
import (
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/gorilla/schema"
logWriter "github.com/newrelic/go-agent/v3/integrations/logcontext-v2/zerologWriter"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/unrolled/secure"
"github.com/kodekoding/phastos/v2/go/common"
"github.com/kodekoding/phastos/v2/go/cron"
"github.com/kodekoding/phastos/v2/go/database"
"github.com/kodekoding/phastos/v2/go/helper"
"github.com/kodekoding/phastos/v2/go/monitoring"
"github.com/kodekoding/phastos/v2/go/server"
)
var decoder = schema.NewDecoder()
type (
Apps interface {
LoadModules()
LoadWrapper()
}
App struct {
Http *chi.Mux
*server.Config
TotalEndpoints int
apiTimeout int
wrapper []Wrapper
cron *cron.Engine
db database.ISQL
trx database.Transactions
newRelic *newrelic.Application
}
Options func(api *App)
Wrapper interface {
WrapToHandler(handler http.Handler) http.Handler
WrapToContext(ctx context.Context) context.Context
}
)
func NewApp(opts ...Options) *App {
apiApp := App{
TotalEndpoints: 0,
}
apiApp.Config = new(server.Config)
apiApp.Config.Ctx = context.Background()
apiApp.Port = 8000
apiApp.ReadTimeout = 3
apiApp.WriteTimeout = 3
apiApp.apiTimeout = 3
for _, opt := range opts {
opt(&apiApp)
}
return &apiApp
}
func WithAppPort(port int) Options {
return func(app *App) {
app.Port = port
}
}
func ReadTimeout(readTimeout int) Options {
return func(app *App) {
app.ReadTimeout = readTimeout
}
}
func WriteTimeout(writeTimeout int) Options {
return func(app *App) {
app.WriteTimeout = writeTimeout
}
}
func WithAPITimeout(apiTimeout int) Options {
return func(app *App) {
app.apiTimeout = apiTimeout
}
}
func WithCronJob(timezone ...string) Options {
return func(app *App) {
cronOpts := cron.WithTimeZone("Asia/Jakarta")
if timezone != nil && len(timezone) > 0 {
cronOpts = cron.WithTimeZone(timezone[0])
}
app.cron = cron.New(cronOpts)
}
}
func WithNewRelic() Options {
return func(app *App) {
newRelicPlatform := monitoring.InitNewRelic()
app.newRelic = newRelicPlatform.GetApp()
}
}
func (app *App) Init() {
app.Http = chi.NewRouter()
app.initPlugins()
// load Notifications if env config is exists
app.loadNotification()
app.loadResources()
}
func (app *App) DB() database.ISQL {
return app.db
}
func (app *App) Trx() database.Transactions {
return app.trx
}
func (app *App) initPlugins() {
app.Http.Use(
middleware.Logger,
middleware.Recoverer,
PanicHandler,
)
app.Http.NotFound(RouteNotFoundHandler)
app.Http.MethodNotAllowed(MethodNotAllowedHandler)
app.Http.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
WriteJson(w, Map{
"message": "pong",
})
})
zerolog.SetGlobalLevel(zerolog.InfoLevel)
var writer io.Writer
writer = zerolog.ConsoleWriter{Out: os.Stderr}
if app.newRelic != nil {
writer = logWriter.New(os.Stdout, app.newRelic)
}
log.Logger = log.Output(writer).With().Str("app", os.Getenv("APP_NAME")).Logger()
}
func (app *App) requestValidator(i interface{}) error {
errorResponse := ValidateStruct(i)
if errorResponse != nil {
return NewErr(
WithErrorCode("VALIDATION_ERROR"),
WithErrorMessage("validation error"),
WithErrorStatus(http.StatusUnprocessableEntity),
WithErrorData(errorResponse),
)
}
return nil
}
func (app *App) wrapHandler(h Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var response *Response
var err error
request := Request{
GetParams: func(key string, defaultValue ...string) string {
var paramValue string
if paramValue = chi.URLParam(r, key); paramValue == "" {
for _, v := range defaultValue {
paramValue = v
}
}
return paramValue
},
GetFile: func(key string) (multipart.File, *multipart.FileHeader, error) {
return r.FormFile(key)
},
GetQuery: func(i interface{}) error {
if err := decoder.Decode(i, r.URL.Query()); err != nil {
return BadRequest(err.Error(), "ERROR_PARSING_QUERY_PARAMS")
}
return app.requestValidator(i)
},
GetHeaders: func(i interface{}) error {
if err := decoder.Decode(i, r.Header); err != nil {
return BadRequest(err.Error(), "ERROR_PARSING_HEADER")
}
return app.requestValidator(i)
},
GetBody: func(i interface{}) error {
contentType := filterFlags(r.Header.Get("Content-Type"))
switch contentType {
case ContentJSON:
if err = json.NewDecoder(r.Body).Decode(i); err != nil {
return BadRequest(err.Error(), ErrParsedBodyCode)
}
case ContentURLEncoded:
if err = parseFormRequest(r); err != nil {
return BadRequest(err.Error(), ErrParsedBodyCode)
}
if err = doHandleDecodeSchema(r, i); err != nil {
return BadRequest(err.Error(), ErrDecodeBodyCode)
}
case ContentFormData:
if err = parseMultiPartFormRequest(r, 32<<20); err != nil {
return BadRequest(err.Error(), ErrParsedBodyCode)
}
if err = doHandleDecodeSchema(r, i); err != nil {
return BadRequest(err.Error(), ErrDecodeBodyCode)
}
default:
log.Warn().Msg("Content-Type Header didn't sent, please defined it, will treat as JSON body payload")
if err = json.NewDecoder(r.Body).Decode(i); err != nil {
return BadRequest(err.Error(), ErrParsedBodyCode)
}
}
return app.requestValidator(i)
},
}
ctx, cancel := context.WithTimeout(r.Context(), time.Second*time.Duration(app.apiTimeout))
defer cancel()
traceId := helper.GenerateUUIDV4()
ctx = context.WithValue(ctx, common.TraceIdKeyContextStr, traceId)
*r = *r.WithContext(ctx)
respChan := make(chan *Response)
go func() {
defer panicRecover(r, traceId)
respChan <- h(request, ctx)
}()
select {
case <-ctx.Done():
if ctx.Err() == context.DeadlineExceeded {
w.WriteHeader(http.StatusGatewayTimeout)
_, err = w.Write([]byte("timeout"))
if err != nil {
log.Error().Msg("context deadline exceed: " + err.Error())
}
}
case response = <-respChan:
if response.Err != nil {
var respErr *HttpError
var ok bool
if respErr, ok = response.Err.(*HttpError); !ok {
respErr = NewErr(WithErrorMessage(response.Err.Error()))
response.SetHTTPError(respErr)
}
respErr.TraceId = traceId
var asyncTrx *newrelic.Transaction
if app.newRelic != nil {
asyncTrx = monitoring.BeginTrxFromContext(ctx).NewGoroutine()
}
go func(asyncTxn *newrelic.Transaction) {
asyncCtx := ctx
if asyncTxn != nil {
asyncCtx = monitoring.NewContext(ctx, asyncTxn)
defer asyncTxn.StartSegment("PhastosAPIApp-WrapHandler-AsyncSentNotifAndLogError").End()
}
// sent error to notification + logs asynchronously
response.SentNotif(asyncCtx, response.InternalError, r, traceId)
logEvent := log.Error()
if response.InternalError.Status < 500 {
// re-assign logEvent from 'error' to 'warn'
logEvent = log.Warn()
}
errData := map[string]interface{}{
"error": response.InternalError,
"request_path": r.URL.String(),
"trace_id": traceId,
}
logEvent.Fields(errData).Msg("Failed processing request")
}(asyncTrx)
}
response.Send(w)
}
}
}
func (app *App) AddController(ctrl Controller) {
config := ctrl.GetConfig()
for _, route := range config.Routes {
middlewares := []func(http.Handler) http.Handler{}
if config.Middlewares != nil {
middlewares = append(middlewares, *config.Middlewares...)
}
if route.Middlewares != nil {
middlewares = append(middlewares, *route.Middlewares...)
}
routePath := route.GetVersionedPath(config.Path)
handlerFunc := app.wrapHandler(route.Handler)
if app.newRelic != nil {
routePath, handlerFunc = newrelic.WrapHandleFunc(app.newRelic, routePath, handlerFunc)
}
handler := chi.
Chain(middlewares...).
HandlerFunc(handlerFunc)
app.Http.Method(route.Method, routePath, handler)
}
app.TotalEndpoints += len(config.Routes)
}
func (app *App) AddControllers(ctrls Controllers) {
controllers := ctrls.Register()
for _, ctrl := range controllers {
app.AddController(ctrl)
}
}
func (app *App) WrapToApp(wrapper Wrapper) {
app.wrapper = append(app.wrapper, wrapper)
}
func (app *App) AddScheduler(pattern string, handler cron.HandlerFunc) {
app.cron.RegisterScheduler(pattern, handler)
}
func (app *App) WrapScheduler(wrapper cron.Wrapper) {
app.cron.Wrap(wrapper)
}
func (app *App) Start() error {
app.Handler = InitHandler(app.Http)
secureMiddleware := secure.New(secure.Options{
BrowserXssFilter: true,
ContentTypeNosniff: true,
})
app.Handler = secureMiddleware.Handler(app.Handler)
corsOptions := cors.Options{
AllowedMethods: []string{"PATCH", "POST", "DELETE", "GET", "PUT", "OPTIONS"},
AllowedHeaders: []string{"Origin", "Referer", "token", "content-type", "Content-Type", "Authorization"},
MaxAge: 60 * 60, //1 hour
}
corsOriginEnv := os.Getenv("CORS_ORIGIN")
if corsOriginEnv != "" {
corsOptions.AllowedOrigins = strings.Split(corsOriginEnv, ",")
}
corsAllowedHeader := os.Getenv("CORS_HEADER")
if corsOriginEnv != "" {
corsOptions.AllowedHeaders = append(corsOptions.AllowedHeaders, strings.Split(corsAllowedHeader, ",")...)
}
corsMiddleware := cors.New(corsOptions)
app.Handler = corsMiddleware.Handler(app.Handler)
for _, wrapper := range app.wrapper {
app.Handler = wrapper.WrapToHandler(app.Handler)
app.Config.Ctx = wrapper.WrapToContext(app.Config.Ctx)
}
log.Info().Msg(fmt.Sprintf("server started on port %d, serving %d endpoint(s)", app.Port, app.TotalEndpoints))
if app.cron != nil {
defer app.cron.Stop()
go app.cron.Start()
}
return server.ServeHTTP(app.Config)
}