fix(logger,middlewares): status code not being read from response

This commit is contained in:
Guz
2024-10-22 11:55:00 -03:00
parent 5448517b67
commit 390774600f
3 changed files with 30 additions and 21 deletions

View File

@@ -10,6 +10,7 @@ import (
"os/signal"
"syscall"
"forge.capytal.company/capytalcode/project-comicverse/configs"
"forge.capytal.company/capytalcode/project-comicverse/handlers/pages"
devPages "forge.capytal.company/capytalcode/project-comicverse/handlers/pages/dev"
"forge.capytal.company/capytalcode/project-comicverse/router"
@@ -56,6 +57,8 @@ func NewApp(opts ...AppOpts) *App {
assets: opts[0].Assets,
}
configs.DEVELOPMENT = app.dev
app.setLogger()
app.setServer()
@@ -75,7 +78,7 @@ func (a *App) setServer() {
r.Use(mlogger.Wrap)
if a.dev {
if configs.DEVELOPMENT {
a.logger.Info("RUNNING IN DEVELOPMENT MODE")
r.Use(middleware.DevMiddleware)

11
assets/assets.go Normal file
View File

@@ -0,0 +1,11 @@
package assets
import (
_ "embed"
)
//go:embed css/uno.css
var UNO_CSS []byte
//go:embed css/theme.css
var THEME_CSS []byte

View File

@@ -4,7 +4,6 @@ import (
"log/slog"
"math/rand"
"net/http"
"strconv"
)
func DevMiddleware(next http.Handler) http.Handler {
@@ -18,6 +17,16 @@ type LoggerMiddleware struct {
log *slog.Logger
}
type loggerReponse struct {
http.ResponseWriter
status int
}
func (lr *loggerReponse) WriteHeader(s int) {
lr.status = s
lr.ResponseWriter.WriteHeader(s)
}
func NewLoggerMiddleware(l *slog.Logger) *LoggerMiddleware {
l = l.WithGroup("logger_middleware")
return &LoggerMiddleware{l}
@@ -34,27 +43,13 @@ func (l *LoggerMiddleware) Wrap(next http.Handler) http.Handler {
slog.String("path", r.URL.Path),
)
next.ServeHTTP(w, r)
lw := &loggerReponse{w, http.StatusOK}
next.ServeHTTP(lw, r)
s := w.Header().Get("Status")
if s == "" {
s = strconv.Itoa(http.StatusOK)
}
sc, err := strconv.Atoi(s)
if err != nil {
l.log.Error("INVALID REQUEST STATUS",
slog.String("id", id),
slog.String("status", s),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
)
return
}
if sc >= 400 {
if lw.status >= 400 {
l.log.Warn("ERR REQUEST",
slog.String("id", id),
slog.String("status", s),
slog.Int("status", lw.status),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
)
@@ -63,7 +58,7 @@ func (l *LoggerMiddleware) Wrap(next http.Handler) http.Handler {
l.log.Info("END REQUEST",
slog.String("id", id),
slog.String("status", s),
slog.Int("status", lw.status),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
)