docs/extra/internal.md
At the heart of Fiber is the App struct. It is responsible for configuring the server, managing a pool of Contexts (either our default implementation, DefaultCtx, or a user‑supplied CustomCtx), and holding the router stack with all registered routes and groups. In addition, the App contains mount fields to support sub‑applications and hooks that allow developers to run custom code at key stages (e.g. when registering routes or starting the server).
flowchart TD
A[App]
B["Configuration (Config)"]
C[Context Pool]
D["DefaultCtx \/ CustomCtx"]
E[Router Stack]
F["Groups & Routes"]
G["MountFields (Sub‑Apps)"]
H[Hooks]
A --> B
A --> C
C --> D
A --> E
E --> F
A --> G
A --> H
Fiber’s request processing is designed for performance and minimal overhead. When an HTTP request is received by the underlying fasthttp server, the flow is as follows:
flowchart LR
R["HTTP Request (fasthttp)"]
A["App.RequestHandler
(default or custom)"]
C["Acquire Context
(from Pool)"]
X["Reset Context
(DefaultCtx.Reset())"]
N["Route Matching
(next() \/ nextCustom())"]
M["Handler Chain Execution"]
EH["Error Handling
(if needed)"]
S["HTTP Response"]
RC["Release Context
(to Pool)"]
R --> A
A --> C
C --> X
X --> N
N --> M
M --> EH
EH --> S
S --> RC
Fiber minimizes memory allocations by reusing Context objects and uses an optimized route‑matching algorithm to rapidly determine the correct handler chain.
Fiber allows you to register routes using helper methods (e.g. Get(), Post()) or by creating groups and sub‑routers. Internally, the route pattern is parsed by the parseRoute() function. This function decomposes the route string into segments:
flowchart TD
P["Route Pattern String
(e.g., '/api/\\:userId\\<int>')"]
PA["parseRoute()"]
RP[routeParser]
RS["routeSegment(s)"]
C["Constraints
(e.g., int, datetime, regex)"]
PARAM[Extracted Parameter Names]
P --> PA
PA --> RP
RP --> RS
RS --> C
RP --> PARAM
When a request is processed, Fiber uses its pre‑computed route tree (the treeStack) to efficiently match the incoming URL against registered routes.
flowchart TD
A["Incoming Request URL
(e.g., '/api/john')"]
B["Normalize URL
(lowercase, trim trailing slashes)"]
C["Detection Path"]
D["Traverse Route Tree
(treeStack based on method)"]
E["Match Constant Segments"]
F["Identify Parameter Segments
(e.g., ':userId')"]
G["Extract Parameter Values"]
H["Validate Constraints
(e.g., 'int', 'datetime', 'regex')"]
I["Route Found"]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
G --> H
H --> I
This efficient matching mechanism leverages pre‑grouped routes to minimize comparisons, while dynamic segments allow for flexible URL structures and runtime validation.
Once a matching route is found, Fiber executes the chain of middleware and route handlers sequentially. The process is as follows:
flowchart TD
A[Matched Route]
B[Handler 1]
C[Handler 2]
D[Handler 3]
E[Response Generation]
A --> B
B -- "Calls C via Next()" --> C
C -- "Calls D via Next()" --> D
D -- "No Next() available" --> E
Middleware are executed in the order they are registered. This sequential design allows each handler to perform tasks such as authentication, logging, or transformation before delegating to the next handler.
Fiber allows mounting sub‑applications (or sub‑routers) under specific path prefixes. This enables modular design of large APIs. The mounting process works as follows:
Use with a sub-app, which triggers the internal mount path logic.flowchart TD
A[Parent App]
B["Sub-App (Mounted)"]
C["Define Mount Point
(e.g. \'/admin\')"]
D["Update MountFields
(assign mount path)"]
E["Merge Sub-App Routes
(append to Router Stack)"]
F[Generate Unified Route Tree]
A --> C
C --> B
B --> D
D --> E
E --> F
This mechanism enables large APIs to be broken down into smaller, maintainable modules while still benefiting from Fiber’s optimized routing and request handling.
Fiber builds a route tree (the treeStack) to optimize route matching. This involves grouping routes based on a prefix (usually the first few characters) to reduce the number of comparisons during a request.
flowchart TD
A["Router Stack
(All Registered Routes)"]
B["Compute Tree Key
(e.g. first 3 characters)"]
C["Group Routes by Key
(treeStack)"]
D["Merge Global Routes
(key \'\' for global matches)"]
E[Sort Routes within Groups]
F[Optimized Route Tree]
A --> B
B --> C
C --> D
D --> E
E --> F
Fiber minimizes allocations by pooling Context objects. The lifecycle of a Context is as follows:
App.AcquireCtx().fasthttp.RequestCtx to clear previous data and initialize new request‑specific values.App.ReleaseCtx(), making it available for reuse.flowchart TD
A["HTTP Request
(fasthttp)"]
B["Acquire Context
(App.AcquireCtx())"]
C["Reset Context
(DefaultCtx.Reset())"]
D["Process Request
(Handlers & Middleware)"]
E["Error Handling
(if needed)"]
F["Release Context
(App.ReleaseCtx())"]
A --> B
B --> C
C --> D
D --> E
E --> F
Reusing Context objects significantly reduces garbage collection overhead, ensuring Fiber remains fast and memory‑efficient even under heavy load.
To take full advantage of multi‑core systems, Fiber offers a prefork mode. In this mode, the master process spawns several child processes that listen on the same port using OS features such as SO_REUSEPORT (or fall back to SO_REUSEADDR).
flowchart LR
M["Master Process (App)"]
C[Child Processes]
GOMAX["Set GOMAXPROCS(1)"]
REQ[Handle HTTP Requests]
WM["watchMaster()"]
M -->|Spawns| C
C --> GOMAX
C -->|Processes| REQ
C --> WM
Fiber’s prefork mode uses OS‑level mechanisms to allow multiple processes to listen on the same port. Here’s a more detailed look:
flowchart TD
A[Master Process]
B[Determine CPU Cores]
C[Spawn Child Processes]
D["Child Process Initialization
(GOMAXPROCS(1))"]
E["Bind to Port
(reuseport)"]
F["Run watchMaster()
(Monitor Parent)"]
G[Handle HTTP Requests]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
Fiber’s redirection mechanism is implemented via the Redirect struct. This structure allows not only setting a new location for redirection but also passing along flash messages and old input data via a special cookie.
flowchart LR
R[Redirect Struct]
RP[redirectPool]
FM["Flash Messages \/ Old Inputs"]
M["Methods:
To(), Route(), Back()"]
LH[Set Location Header]
CK["Flash Cookie
(fiber\_flash)"]
R -->|Acquired from| RP
R --> FM
R --> M
M --> LH
FM -->|Serialized| CK
When performing redirections, Fiber can send flash messages or preserve old input data. This process involves:
flowchart TD
A[Initiate Redirect]
B["Add Flash Messages
(With(), WithInput())"]
C[Serialize Flash Data]
D["Set Flash Cookie
(\'fiber\_flash\')"]
E[Client Receives Redirect]
F[Next Request Reads Flash Cookie]
G["Deserialize & Clear Flash Data"]
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
Fiber provides a comprehensive hook system that allows you to run custom functions at key moments:
flowchart TD
H[Hooks]
OR[OnRoute]
ON[OnName]
OG[OnGroup]
OL[OnListen]
OS[OnShutdown]
OF[OnFork]
OM[OnMount]
H --> OR
H --> ON
H --> OG
H --> OL
H --> OS
H --> OF
H --> OM
Fiber’s DefaultCtx (or CustomCtx) represents the per‑request context. The lifecycle is as follows:
flowchart LR
AC["Acquire Context
(from Pool)"]
HP["Handle Request
(Handlers & Middleware)"]
EH["Error Handling
(if needed)"]
RC["Release Context
(to Pool)"]
AC --> HP
HP --> EH
EH --> RC