Dynamic Route Management
This recipe demonstrates how to manage dynamic routes at runtime in Fiber v3 without restarting the application.
Note on Router Thread-Safety: Fiber v3 can also add and remove real routes at runtime with
app.RebuildTree()andapp.RemoveRoute(), but those calls are not thread-safe while the server handles requests. This recipe keeps its routes in async.RWMutex-protected registry instead and serves them through one/d/*handler, so the router itself never changes.
It provides:
- A thread-safe runtime
RouteManagerusingsync.RWMutex. - Admin management endpoints to register, list, and unregister dynamic routes, protected by the
keyauthmiddleware. - Route stack inspection using Fiber's native
app.Stack(). - A dynamic dispatcher route (
/d/*) to evaluate and execute active routes.
Note: The admin routes require the API key from
ADMIN_API_KEYas a bearer token, because anyone who can call them can publish content under/d/*. The server refuses to start without it. The key travels in plain text over HTTP, so put TLS in front (app.Listenwithfiber.ListenConfig{CertFile: ..., CertKeyFile: ...}, or a reverse proxy) before the server is reachable from other hosts.
Prerequisites
Ensure you have the following installed:
- Go 1.27.0 or newer
- Fiber v3 package (
github.com/gofiber/fiber/v3)
Setup
Navigate to the recipe directory:
cd recipes/dynamic-routingDownload and verify dependencies:
go mod tidy
Running the Application
In your terminal, start the server:
export ADMIN_API_KEY=change-me go run main.goIn a separate terminal, export the same key and test the endpoints using
curl:export ADMIN_API_KEY=change-meList active routes (static stack and dynamic registry):
curl -s http://127.0.0.1:3000/admin/routes \ -H "Authorization: Bearer $ADMIN_API_KEY" | jq .Access pre-seeded dynamic route:
curl -s http://127.0.0.1:3000/d/promo | jq .Register a new dynamic route at runtime:
curl -s -X POST http://127.0.0.1:3000/admin/routes \ -H "Authorization: Bearer $ADMIN_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "flash-sale", "path": "/flash", "response": "Limited time offer 50% off!"}' | jq .The path must start with
/. Registering a path that already exists returns409 Conflict.Execute the newly registered dynamic route:
curl -s http://127.0.0.1:3000/d/flash | jq .Remove the dynamic route:
curl -s -X DELETE http://127.0.0.1:3000/admin/routes/flash \ -H "Authorization: Bearer $ADMIN_API_KEY" | jq .
Example Code
package main
import (
"log"
"sync"
"github.com/gofiber/fiber/v3"
)
type DynamicRoute struct {
Name string `json:"name"`
Path string `json:"path"`
Response string `json:"response"`
}
type RouteManager struct {
mu sync.RWMutex
routes map[string]DynamicRoute
}
// See main.go for full implementation