โ๏ธ Middlewares
In Velora, middlewares provide a way to add custom logic before or after request handling. They can be applied globally (to all routes) or locally (to a specific module). Velora uses a centralized middlewareRegistry to manage them.
๐๏ธ Middleware Registry
All middlewares must be registered inside Velora before they can be used globally or in modules. The registry keeps track of available middlewares by name:
package app
import "github.com/gofiber/fiber/v2"
// Alias for Fiber handler
type MiddlewareFunc = fiber.Handler
// Global registry
var middlewareRegistry = map[string]MiddlewareFunc{}
// Register a new middleware by name
func RegisterMiddleware(name string, fn MiddlewareFunc) {
middlewareRegistry[name] = fn
}
// Retrieve a middleware by name
func GetMiddleware(name string) (MiddlewareFunc, bool) {
fn, ok := middlewareRegistry[name]
return fn, ok
}RegisterMiddlewareโ Adds a middleware to the global registry with a unique name.GetMiddlewareโ Retrieves a middleware by name. Returnsfalseif not found.- Important: A middleware must be registered before it can be used.
๐ Global Middlewares
Global middlewares apply to all routes in the application. They are attached using UseGlobalMiddleware:
app := velora.New()
// Register custom middlewares
velora.RegisterMiddleware("logging", func(c *fiber.Ctx) error {
fmt.Println("[LOG]", c.Path())
return c.Next()
})
velora.RegisterMiddleware("cors", func(c *fiber.Ctx) error {
c.Set("Access-Control-Allow-Origin", "*")
return c.Next()
})
// Attach them globally
app.UseGlobalMiddleware("logging", "cors")If a global middleware is not found in the registry, Velora will print a โ ๏ธ warning but continue running.
๐ฆ Module Middlewares
Each module must implement the Middlewares() []string method. This returns an array of middleware names that are applied only to that moduleโs routes.
func (m *AppModule) Middlewares() []string {
return []string{"auth", "logging"} // required for every module
}โ Important: Every module must define Middlewares(). Even if the module has no specific middlewares, it should return an empty array:
func (m *EmptyModule) Middlewares() []string {
return []string{} // required to avoid runtime error
}๐ Example: Auth Middleware
Hereโs an example of a simple authentication guard middleware:
velora.RegisterMiddleware("auth", func(c *fiber.Ctx) error {
token := c.Get("Authorization")
if token == "" {
return c.Status(401).SendString("Unauthorized")
}
return c.Next()
})Modules that require authentication can simply return []string{"auth} in their Middlewares.
๐ Summary
- Register middlewares globally with
RegisterMiddleware. - Apply them globally with
UseGlobalMiddleware. - Each module must implement
Middlewares(). - Middlewares can be applied per-module or globally, depending on the use case.
Next, learn how to configure Velora to integrate databases, Redis, and more.