diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/README.md
index 60e4c2888ff..da02e963bfb 100644
--- a/contrib_versioned_docs/version-opafiber_v2.x.x/README.md
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/README.md
@@ -8,7 +8,6 @@ sidebar_position: 1
-
[](https://gofiber.io/discord)


@@ -21,14 +20,17 @@ Repository for third party middlewares with dependencies.
## 📑 Middleware Implementations
* [Casbin](./casbin/README.md)
+* [Fgprof](./fgprof/README.md)
* [Fiberi18n](./fiberi18n/README.md)
* [Fibersentry](./fibersentry/README.md)
* [Fiberzap](./fiberzap/README.md)
* [Fiberzerolog](./fiberzerolog/README.md)
* [JWT](./jwt/README.md)
+* [Loadshed](./loadshed/README.md)
* [NewRelic](./fibernewrelic/README.md)
* [Open Policy Agent](./opafiber/README.md)
* [Otelfiber (OpenTelemetry)](./otelfiber/README.md)
* [Paseto](./paseto/README.md)
+* [Socket.io](./socketio/README.md)
* [Swagger](./swagger/README.md)
* [Websocket](./websocket/README.md)
diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/fgprof/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/fgprof/README.md
new file mode 100644
index 00000000000..74a87f1f259
--- /dev/null
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/fgprof/README.md
@@ -0,0 +1,59 @@
+---
+id: fgprof
+---
+
+# Fgprof
+
+
+[](https://gofiber.io/discord)
+
+
+
+
+[fgprof](https://github.com/felixge/fgprof) support for Fiber.
+
+**Note: Requires Go 1.19 and above**
+
+## Install
+
+This middleware supports Fiber v2.
+
+Using fgprof to profiling your Fiber app.
+
+```
+go get -u github.com/gofiber/fiber/v2
+go get -u github.com/gofiber/contrib/fgprof
+```
+
+## Config
+
+| Property | Type | Description | Default |
+|----------|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|---------|
+| Next | `func(c *fiber.Ctx) bool` | A function to skip this middleware when returned `true`. | `nil` |
+| Prefix | `string`. | Prefix defines a URL prefix added before "/debug/fgprof". Note that it should start with (but not end with) a slash. Example: "/federated-fiber" | `""` |
+
+## Example
+
+```go
+package main
+
+import (
+ "log"
+
+ "github.com/gofiber/contrib/fgprof"
+ "github.com/gofiber/fiber/v2"
+)
+
+func main() {
+ app := fiber.New()
+ app.Use(fgprof.New())
+ app.Get("/", func(c *fiber.Ctx) error {
+ return c.SendString("OK")
+ })
+ log.Fatal(app.Listen(":3000"))
+}
+```
+
+```bash
+go tool pprof -http=:8080 http://localhost:3000/debug/fgprof
+```
diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/fiberzerolog/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/fiberzerolog/README.md
index 732dbd377e6..46e7f5a5612 100644
--- a/contrib_versioned_docs/version-opafiber_v2.x.x/fiberzerolog/README.md
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/fiberzerolog/README.md
@@ -38,11 +38,12 @@ fiberzerolog.New(config ...fiberzerolog.Config) fiber.Handler
| Logger | `*zerolog.Logger` | Add custom zerolog logger. | `zerolog.New(os.Stderr).With().Timestamp().Logger()` |
| GetLogger | `func(*fiber.Ctx) zerolog.Logger` | Get custom zerolog logger, if it's defined the returned logger will replace the `Logger` value. | `nil` |
| Fields | `[]string` | Add fields what you want see. | `[]string{"latency", "status", "method", "url", "error"}` |
+| WrapHeaders | bool | Wrap headers to dictionary.
If false: `{"method":"POST", "header-key":"header value"}`
If true: `{"method":"POST", "reqHeaders": {"header-key":"header value"}}` | `false` |
+| FieldsSnakeCase | bool | Use snake case for fields: FieldResBody, FieldQueryParams, FieldBytesReceived, FieldBytesSent, FieldRequestId, FieldReqHeaders, FieldResHeaders.
If false: `{"method":"POST", "resBody":"v", "queryParams":"v"}`
If true: `{"method":"POST", "res_body":"v", "query_params":"v"}` | `false` |
| Messages | `[]string` | Custom response messages. | `[]string{"Server error", "Client error", "Success"}` |
| Levels | `[]zerolog.Level` | Custom response levels. | `[]zerolog.Level{zerolog.ErrorLevel, zerolog.WarnLevel, zerolog.InfoLevel}` |
| SkipURIs | `[]string` | Skip logging these URI. | `[]string{}` |
-| GetResBody | func(c *fiber.Ctx) []byte | Define a function to get response body when return non-nil.
eg: When use compress middleware, resBody is unreadable. you can set GetResBody func to get readable resBody. | `nil` |
-
+| GetResBody | func(c *fiber.Ctx) []byte | Define a function to get response body when return non-nil.
eg: When use compress middleware, resBody is unreadable. you can set GetResBody func to get readable resBody. | `nil` |
## Example
```go
diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/loadshed/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/loadshed/README.md
new file mode 100644
index 00000000000..be0b0a8a515
--- /dev/null
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/loadshed/README.md
@@ -0,0 +1,121 @@
+---
+id: loadshed
+---
+
+# LoadShed
+
+
+[](https://gofiber.io/discord)
+
+
+
+
+The LoadShed middleware for [Fiber](https://github.com/gofiber/fiber) is designed to help manage server load by shedding requests based on certain load criteria.
+
+**Note: Requires Go 1.19 and above**
+
+## Install
+
+This middleware supports Fiber v2
+
+```
+go get -u github.com/gofiber/fiber/v2
+go get -u github.com/gofiber/contrib/loadshed
+```
+
+## Signatures
+
+```go
+loadshed.New(config ...loadshed.Config) fiber.Handler
+```
+
+## Examples
+
+To use the LoadShed middleware in your Fiber application, import it and apply it to your Fiber app. Here's an example:
+
+```go
+package main
+
+import (
+ "github.com/gofiber/fiber/v2"
+ loadshed "github.com/gofiber/contrib/loadshed"
+)
+
+func main() {
+ app := fiber.New()
+
+ // Configure and use LoadShed middleware
+ app.Use(loadshed.New(loadshed.Config{
+ Criteria: &loadshed.CPULoadCriteria{
+ LowerThreshold: 0.75, // Set your own lower threshold
+ UpperThreshold: 0.90, // Set your own upper threshold
+ Interval: 10 * time.Second,
+ Getter: &loadshed.DefaultCPUPercentGetter{},
+ },
+ }))
+
+ app.Get("/", func(c *fiber.Ctx) error {
+ return c.SendString("Welcome!")
+ })
+
+ app.Listen(":3000")
+}
+```
+
+## Config
+
+The LoadShed middleware in Fiber offers various configuration options to tailor the load shedding behavior according to the needs of your application.
+
+| Property | Type | Description | Default |
+| :------- | :---------------------- | :--------------------------------------------------- | :---------------------- |
+| Next | `func(*fiber.Ctx) bool` | Function to skip this middleware when returned true. | `nil` |
+| Criteria | `LoadCriteria` | Interface for defining load shedding criteria. | `&CPULoadCriteria{...}` |
+
+## LoadCriteria
+
+LoadCriteria is an interface in the LoadShed middleware that defines the criteria for determining when to shed load in the system. Different implementations of this interface can use various metrics and algorithms to decide when and how to shed incoming requests to maintain system performance.
+
+### CPULoadCriteria
+
+`CPULoadCriteria` is an implementation of the `LoadCriteria` interface, using CPU load as the metric for determining whether to shed requests.
+
+#### Properties
+
+| Property | Type | Description |
+| :------------- | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
+| LowerThreshold | `float64` | The lower CPU usage threshold as a fraction (0.0 to 1.0). Requests are considered for shedding when CPU usage exceeds this threshold. |
+| UpperThreshold | `float64` | The upper CPU usage threshold as a fraction (0.0 to 1.0). All requests are shed when CPU usage exceeds this threshold. |
+| Interval | `time.Duration` | The time interval over which the CPU usage is averaged for decision making. |
+| Getter | `CPUPercentGetter` | Interface to retrieve CPU usage percentages. |
+
+#### How It Works
+
+`CPULoadCriteria` determines the load on the system based on CPU usage and decides whether to shed incoming requests. It operates on the following principles:
+
+- **CPU Usage Measurement**: It measures the CPU usage over a specified interval.
+- **Thresholds**: Utilizes `LowerThreshold` and `UpperThreshold` values to decide when to start shedding requests.
+- **Proportional Rejection Probability**:
+ - **Below `LowerThreshold`**: No requests are rejected, as the system is considered under acceptable load.
+ - **Between `LowerThreshold` and `UpperThreshold`**: The probability of rejecting a request increases as the CPU usage approaches the `UpperThreshold`. This is calculated using the formula:
+ ```plaintext
+ rejectionProbability := (cpuUsage - LowerThreshold*100) / (UpperThreshold - LowerThreshold)
+ ```
+ - **Above `UpperThreshold`**: All requests are rejected to prevent system overload.
+
+This mechanism ensures that the system can adaptively manage its load, maintaining stability and performance under varying traffic conditions.
+
+## Default Config
+
+This is the default configuration for `LoadCriteria` in the LoadShed middleware.
+
+```go
+var ConfigDefault = Config{
+ Next: nil,
+ Criteria: &CPULoadCriteria{
+ LowerThreshold: 0.90, // 90% CPU usage as the start point for considering shedding
+ UpperThreshold: 0.95, // 95% CPU usage as the point where all requests are shed
+ Interval: 10 * time.Second, // CPU usage is averaged over 10 seconds
+ Getter: &DefaultCPUPercentGetter{}, // Default method for getting CPU usage
+ },
+}
+```
diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/otelfiber/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/otelfiber/README.md
index 56032fad307..5d3a215b4b4 100644
--- a/contrib_versioned_docs/version-opafiber_v2.x.x/otelfiber/README.md
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/otelfiber/README.md
@@ -26,22 +26,25 @@ go get -u github.com/gofiber/contrib/otelfiber/v2
## Signature
-```
+```go
otelfiber.Middleware(opts ...otelfiber.Option) fiber.Handler
```
## Config
+You can configure the middleware using functional parameters
-| Property | Type | Description | Default |
+
+| Function | Argument Type | Description | Default |
| :------------------ | :-------------------------------- | :--------------------------------------------------------------------------------- | :-------------------------------------------------------------------- |
-| Next | `func(*fiber.Ctx) bool` | Define a function to skip this middleware when returned trueRequired - Rego quer | nil |
-| TracerProvider | `oteltrace.TracerProvider` | Specifies a tracer provider to use for creating a tracer | nil - the global tracer provider is used |
-| MeterProvider | `otelmetric.MeterProvider` | Specifies a meter provider to use for reporting | nil - the global meter provider is used |
-| Port | `*int` | Specifies the value to use when setting the `net.host.port` attribute on metrics/spans | Required: If not default (`80` for `http`, `443` for `https`) |
-| Propagators | `propagation.TextMapPropagator` | Specifies propagators to use for extracting information from the HTTP requests | If none are specified, global ones will be used |
-| ServerName | `*string` | specifies the value to use when setting the `http.server_name` attribute on metrics/spans | - |
-| SpanNameFormatter | `func(*fiber.Ctx) string` | Takes a function that will be called on every request and the returned string will become the Span Name | default formatter returns the route pathRaw |
-| CustomAttributes | `func(*fiber.Ctx) []attribute.KeyValue` | Define a function to add custom attributes to the span | nil |
+| `WithNext` | `func(*fiber.Ctx) bool` | Define a function to skip this middleware when returned true .| nil |
+| `WithTracerProvider` | `oteltrace.TracerProvider` | Specifies a tracer provider to use for creating a tracer. | nil - the global tracer provider is used |
+| `WithMeterProvider` | `otelmetric.MeterProvider` | Specifies a meter provider to use for reporting. | nil - the global meter provider is used |
+| `WithPort` | `int` | Specifies the value to use when setting the `net.host.port` attribute on metrics/spans. | Defaults to (`80` for `http`, `443` for `https`) |
+| `WithPropagators` | `propagation.TextMapPropagator` | Specifies propagators to use for extracting information from the HTTP requests. | If none are specified, global ones will be used |
+| `WithServerName` | `string` | Specifies the value to use when setting the `http.server_name` attribute on metrics/spans. | - |
+| `WithSpanNameFormatter` | `func(*fiber.Ctx) string` | Takes a function that will be called on every request and the returned string will become the span Name. | Default formatter returns the route pathRaw |
+| `WithCustomAttributes` | `func(*fiber.Ctx) []attribute.KeyValue` | Define a function to add custom attributes to the span. | nil |
+| `WithCollectClientIP` | `bool` | Specifies whether to collect the client's IP address from the request. | true |
## Usage
@@ -127,4 +130,4 @@ func getUser(ctx context.Context, id string) string {
}
return "unknown"
}
-```
\ No newline at end of file
+```
diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/socketio/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/socketio/README.md
new file mode 100644
index 00000000000..976495c19d9
--- /dev/null
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/socketio/README.md
@@ -0,0 +1,235 @@
+id: socketio
+---
+
+# Socket.io
+
+
+
+
+
+
+WebSocket wrapper for [Fiber](https://github.com/gofiber/fiber) with events support and inspired by [Socket.io](https://github.com/socketio/socket.io)
+
+**Note: Requires Go 1.20 and above**
+
+## Install
+
+```
+go get -u github.com/gofiber/fiber/v2
+go get -u github.com/gofiber/contrib/socketio
+```
+
+## Signatures
+
+```go
+// Initialize new socketio in the callback this will
+// execute a callback that expects kws *Websocket Object
+func New(callback func(kws *Websocket)) func(*fiber.Ctx) error
+```
+
+```go
+// Add listener callback for an event into the listeners list
+func On(event string, callback func(payload *EventPayload))
+```
+
+```go
+// Emit the message to a specific socket uuids list
+// Ignores all errors
+func EmitToList(uuids []string, message []byte)
+```
+
+```go
+// Emit to a specific socket connection
+func EmitTo(uuid string, message []byte) error
+```
+
+```go
+// Broadcast to all the active connections
+// except avoid broadcasting the message to itself
+func Broadcast(message []byte)
+```
+
+```go
+// Fire custom event on all connections
+func Fire(event string, data []byte)
+```
+
+## Example
+
+```go
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+
+ "github.com/gofiber/contrib/socketio"
+ "github.com/gofiber/contrib/websocket"
+ "github.com/gofiber/fiber/v2"
+)
+
+// MessageObject Basic chat message object
+type MessageObject struct {
+ Data string `json:"data"`
+ From string `json:"from"`
+ Event string `json:"event"`
+ To string `json:"to"`
+}
+
+func main() {
+
+ // The key for the map is message.to
+ clients := make(map[string]string)
+
+ // Start a new Fiber application
+ app := fiber.New()
+
+ // Setup the middleware to retrieve the data sent in first GET request
+ app.Use(func(c *fiber.Ctx) error {
+ // IsWebSocketUpgrade returns true if the client
+ // requested upgrade to the WebSocket protocol.
+ if websocket.IsWebSocketUpgrade(c) {
+ c.Locals("allowed", true)
+ return c.Next()
+ }
+ return fiber.ErrUpgradeRequired
+ })
+
+ // Multiple event handling supported
+ socketio.On(socketio.EventConnect, func(ep *socketio.EventPayload) {
+ fmt.Println(fmt.Sprintf("Connection event 1 - User: %s", ep.Kws.GetStringAttribute("user_id")))
+ })
+
+ // Custom event handling supported
+ socketio.On("CUSTOM_EVENT", func(ep *socketio.EventPayload) {
+ fmt.Println(fmt.Sprintf("Custom event - User: %s", ep.Kws.GetStringAttribute("user_id")))
+ // --->
+
+ // DO YOUR BUSINESS HERE
+
+ // --->
+ })
+
+ // On message event
+ socketio.On(socketio.EventMessage, func(ep *socketio.EventPayload) {
+
+ fmt.Println(fmt.Sprintf("Message event - User: %s - Message: %s", ep.Kws.GetStringAttribute("user_id"), string(ep.Data)))
+
+ message := MessageObject{}
+
+ // Unmarshal the json message
+ // {
+ // "from": "",
+ // "to": "",
+ // "event": "CUSTOM_EVENT",
+ // "data": "hello"
+ //}
+ err := json.Unmarshal(ep.Data, &message)
+ if err != nil {
+ fmt.Println(err)
+ return
+ }
+
+ // Fire custom event based on some
+ // business logic
+ if message.Event != "" {
+ ep.Kws.Fire(message.Event, []byte(message.Data))
+ }
+
+ // Emit the message directly to specified user
+ err = ep.Kws.EmitTo(clients[message.To], ep.Data, socketio.TextMessage)
+ if err != nil {
+ fmt.Println(err)
+ }
+ })
+
+ // On disconnect event
+ socketio.On(socketio.EventDisconnect, func(ep *socketio.EventPayload) {
+ // Remove the user from the local clients
+ delete(clients, ep.Kws.GetStringAttribute("user_id"))
+ fmt.Println(fmt.Sprintf("Disconnection event - User: %s", ep.Kws.GetStringAttribute("user_id")))
+ })
+
+ // On close event
+ // This event is called when the server disconnects the user actively with .Close() method
+ socketio.On(socketio.EventClose, func(ep *socketio.EventPayload) {
+ // Remove the user from the local clients
+ delete(clients, ep.Kws.GetStringAttribute("user_id"))
+ fmt.Println(fmt.Sprintf("Close event - User: %s", ep.Kws.GetStringAttribute("user_id")))
+ })
+
+ // On error event
+ socketio.On(socketio.EventError, func(ep *socketio.EventPayload) {
+ fmt.Println(fmt.Sprintf("Error event - User: %s", ep.Kws.GetStringAttribute("user_id")))
+ })
+
+ app.Get("/ws/:id", socketio.New(func(kws *socketio.Websocket) {
+
+ // Retrieve the user id from endpoint
+ userId := kws.Params("id")
+
+ // Add the connection to the list of the connected clients
+ // The UUID is generated randomly and is the key that allow
+ // socketio to manage Emit/EmitTo/Broadcast
+ clients[userId] = kws.UUID
+
+ // Every websocket connection has an optional session key => value storage
+ kws.SetAttribute("user_id", userId)
+
+ //Broadcast to all the connected users the newcomer
+ kws.Broadcast([]byte(fmt.Sprintf("New user connected: %s and UUID: %s", userId, kws.UUID)), true, socketio.TextMessage)
+ //Write welcome message
+ kws.Emit([]byte(fmt.Sprintf("Hello user: %s with UUID: %s", userId, kws.UUID)), socketio.TextMessage)
+ }))
+
+ log.Fatal(app.Listen(":3000"))
+}
+
+```
+
+---
+
+## Supported events
+
+| Const | Event | Description |
+|:----------------|:-------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------|
+| EventMessage | `message` | Fired when a Text/Binary message is received |
+| EventPing | `ping` | [More details here](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Pings_and_Pongs_The_Heartbeat_of_WebSockets) |
+| EventPong | `pong` | Refer to ping description |
+| EventDisconnect | `disconnect` | Fired on disconnection. The error provided in disconnection event as defined in RFC 6455, section 11.7. |
+| EventConnect | `connect` | Fired on first connection |
+| EventClose | `close` | Fired when the connection is actively closed from the server. Different from client disconnection |
+| EventError | `error` | Fired when some error appears useful also for debugging websockets |
+
+## Event Payload object
+
+| Variable | Type | Description |
+|:-----------------|:--------------------|:--------------------------------------------------------------------------------|
+| Kws | `*Websocket` | The connection object |
+| Name | `string` | The name of the event |
+| SocketUUID | `string` | Unique connection UUID |
+| SocketAttributes | `map[string]string` | Optional websocket attributes |
+| Error | `error` | (optional) Fired from disconnection or error events |
+| Data | `[]byte` | Data used on Message and on Error event, contains the payload for custom events |
+
+## Socket instance functions
+
+| Name | Type | Description |
+|:-------------|:---------|:----------------------------------------------------------------------------------|
+| SetAttribute | `void` | Set a specific attribute for the specific socket connection |
+| GetUUID | `string` | Get socket connection UUID |
+| SetUUID | `error` | Set socket connection UUID |
+| GetAttribute | `string` | Get a specific attribute from the socket attributes |
+| EmitToList | `void` | Emit the message to a specific socket uuids list |
+| EmitTo | `error` | Emit to a specific socket connection |
+| Broadcast | `void` | Broadcast to all the active connections except broadcasting the message to itself |
+| Fire | `void` | Fire custom event |
+| Emit | `void` | Emit/Write the message into the given connection |
+| Close | `void` | Actively close the connection from the server |
+
+**Note: the FastHTTP connection can be accessed directly from the instance**
+
+```go
+kws.Conn
+```
diff --git a/contrib_versioned_docs/version-opafiber_v2.x.x/swagger/README.md b/contrib_versioned_docs/version-opafiber_v2.x.x/swagger/README.md
index f43493da7e2..b928f4f555e 100644
--- a/contrib_versioned_docs/version-opafiber_v2.x.x/swagger/README.md
+++ b/contrib_versioned_docs/version-opafiber_v2.x.x/swagger/README.md
@@ -48,7 +48,7 @@ import (
Using the default config:
```go
-app.Use(swagger.New(cfg))
+app.Use(swagger.New())
```
Using a custom config:
@@ -129,4 +129,4 @@ var ConfigDefault = Config{
Title: "Fiber API documentation",
CacheAge: 3600, // Default to 1 hour
}
-```
\ No newline at end of file
+```