3
0
corteza/pkg/api/server/middleware.go
Denis Arh d74239c735 Improve HTTP server startup, add wrapping handler
HTTP server now initializes much earlier and mounts "waiting"
router with debugging, version and health check routes.

When server is fully activated it switches to "active"
router.

Shutdown stage is also handled with catch-all route.
2022-02-13 18:52:59 +01:00

57 lines
1.3 KiB
Go

package server
import (
"context"
"net/http"
"os"
"runtime/debug"
"github.com/cortezaproject/corteza-server/pkg/api"
"github.com/cortezaproject/corteza-server/pkg/locale"
"github.com/cortezaproject/corteza-server/pkg/logger"
"github.com/getsentry/sentry-go/http"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
)
func BaseMiddleware(isProduction bool, log *zap.Logger) []func(http.Handler) http.Handler {
return []func(http.Handler) http.Handler{
handleCORS,
locale.DetectLanguage(locale.Global()),
middleware.RealIP,
api.RemoteAddrToContext,
middleware.RequestID,
api.DebugToContext(isProduction),
contextLogger(log),
}
}
func sentryMiddleware() func(http.Handler) http.Handler {
return sentryhttp.New(sentryhttp.Options{
Repanic: true,
}).Handle
}
func panicRecovery(ctx context.Context, w http.ResponseWriter) {
if err := recover(); err != nil {
log := logger.ContextValue(ctx)
if err, ok := err.(error); ok {
log = log.With(zap.Error(err))
} else {
log = log.With(zap.Any("recover-value", err))
}
log.Debug("crashed on http request", zap.ByteString("stack", debug.Stack()))
w.WriteHeader(500)
if _, has := os.LookupEnv("DEBUG_DUMP_STACK_IN_RESPONSE"); has {
// Provide nice call stack on endpoint when
// we crash
_, _ = w.Write(debug.Stack())
}
return
}
}