searcherside/infrastructure/api/middlewares/logging_middleware.go
Peter Kurfer 9ea9a8f658
Some checks failed
Go build / build (push) Failing after 1m58s
feat: continue basic setup
- setup ent scheme
- add command to create users
- document API
- add helpers to create migrations
- add command to run migrations
- add basic compose file
2024-06-19 21:19:37 +02:00

38 lines
1.1 KiB
Go

package middlewares
import (
"encoding/hex"
"hash/fnv"
"log/slog"
"net/http"
"strconv"
"time"
"code.icb4dc0.de/prskr/searcherside/infrastructure/logging"
)
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
requestLogger := logging.GetLogger(request.Context()).With(
slog.String("http.requestId", requestId(request)),
slog.String("http.method", request.Method),
slog.String("http.path", request.URL.Path),
)
requestLogger.Info("Handling incoming request")
next.ServeHTTP(writer, request.WithContext(logging.ContextWithLogger(request.Context(), requestLogger)))
requestLogger.Info("Handled incoming request")
})
}
func requestId(req *http.Request) string {
hash := fnv.New64()
_, _ = hash.Write([]byte(req.Method))
_, _ = hash.Write([]byte(req.RequestURI))
_, _ = hash.Write([]byte(req.RemoteAddr))
_, _ = hash.Write([]byte(req.UserAgent()))
_, _ = hash.Write(strconv.AppendInt(nil, time.Now().UTC().UnixNano(), 10))
return hex.EncodeToString(hash.Sum(nil))
}