You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/google/uuid"
|
|
|
|
"knowfoolery/backend/shared/infra/auth/zitadel"
|
|
"knowfoolery/backend/shared/infra/observability/logging"
|
|
)
|
|
|
|
const requestIDKey = "request_id"
|
|
|
|
// RequestContext injects request id metadata and logs request completion.
|
|
func RequestContext(logger *logging.Logger) fiber.Handler {
|
|
return func(c fiber.Ctx) error {
|
|
reqID := c.Get("X-Request-ID")
|
|
if reqID == "" {
|
|
reqID = uuid.NewString()
|
|
}
|
|
c.Locals(requestIDKey, reqID)
|
|
c.Set("X-Request-ID", reqID)
|
|
|
|
started := time.Now()
|
|
err := c.Next()
|
|
|
|
userID := ""
|
|
if raw := c.Locals(string(zitadel.ContextKeyUserID)); raw != nil {
|
|
if s, ok := raw.(string); ok {
|
|
userID = s
|
|
}
|
|
}
|
|
|
|
if logger != nil {
|
|
logger.APIRequest(
|
|
c.Method(),
|
|
c.Path(),
|
|
c.Response().StatusCode(),
|
|
time.Since(started),
|
|
userID,
|
|
)
|
|
}
|
|
|
|
return err
|
|
}
|
|
}
|
|
|
|
// RequestID returns the request identifier for current request.
|
|
func RequestID(c fiber.Ctx) string {
|
|
if raw := c.Locals(requestIDKey); raw != nil {
|
|
if s, ok := raw.(string); ok {
|
|
return s
|
|
}
|
|
}
|
|
return ""
|
|
}
|