### Install Monitor Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/monitor/README.md Install the Fiber framework and the Monitor middleware using go get. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/monitor ``` -------------------------------- ### Install Zerolog for Fiber Source: https://github.com/gofiber/contrib/blob/main/v3/zerolog/README.md Install the necessary Fiber and Zerolog packages using go get. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/zerolog go get -u github.com/rs/zerolog/log ``` -------------------------------- ### Install Fiber and Websocket Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/websocket/README.md Install the necessary Fiber and Websocket packages using go get. ```go go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/websocket ``` -------------------------------- ### Start Fiber Server and Client Services Source: https://github.com/gofiber/contrib/blob/main/v3/otel/example/README.md Use Docker Compose to bring up the necessary services for the GoFiber OpenTelemetry example. Ensure Docker Compose is installed. ```sh docker-compose up --detach fiber-server fiber-client ``` -------------------------------- ### Install OTel Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/otel/README.md Install the OpenTelemetry middleware for Fiber v3 using go get. ```sh go get -u github.com/gofiber/contrib/v3/otel ``` -------------------------------- ### Install Socket.IO Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Install the Socket.IO middleware for GoFiber using go get. ```go go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/socketio ``` -------------------------------- ### Basic Fiber Zap Logging Example Source: https://github.com/gofiber/contrib/blob/main/v3/zap/README.md Demonstrates how to initialize Fiber and apply the Zap logging middleware with a production logger. This setup logs requests and responses. ```go package main import ( "log" middleware "github.com/gofiber/contrib/v3/zap" "github.com/gofiber/fiber/v3" "go.uber.org/zap" ) func main() { app := fiber.New() logger, _ := zap.NewProduction() defer logger.Sync() app.Use(middleware.New(middleware.Config{ Logger: logger, })) app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello, World!") }) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### Install Circuit Breaker Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/circuitbreaker/README.md Install the Fiber framework and the Circuit Breaker middleware using go get. ```bash go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/circuitbreaker ``` -------------------------------- ### Install Coraza Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/coraza/README.md Install the Coraza middleware and Fiber using go get. ```sh go get github.com/gofiber/fiber/v3 go get github.com/gofiber/contrib/v3/coraza ``` -------------------------------- ### Install Swagger UI Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/swaggerui/README.md Install the Swagger UI middleware using go get. Ensure you have initialized a Go module first. ```bash go mod init github.com// go get github.com/gofiber/contrib/v3/swaggerui ``` -------------------------------- ### Install Swaggo Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/swaggo/README.md Install the Swaggo middleware for Fiber v3 using go get. ```bash go get github.com/gofiber/contrib/v3/swaggo ``` -------------------------------- ### Basic OPA Middleware Usage Source: https://github.com/gofiber/contrib/blob/main/v3/opa/README.md Example of setting up OPA middleware with a custom Rego policy and input creation method. ```go package main import ( "bytes" "github.com/gofiber/fiber/v3" "github.com/gofiber/contrib/v3/opa" ) func main() { app := fiber.New() module := ` package example.authz default allow := false allow if { input.method == "GET" } ` cfg := opa.Config{ RegoQuery: "data.example.authz.allow", RegoPolicy: bytes.NewBufferString(module), IncludeQueryString: true, DeniedStatusCode: fiber.StatusForbidden, DeniedResponseMessage: "status forbidden", IncludeHeaders: []string{"Authorization"}, InputCreationMethod: func(ctx fiber.Ctx) (map[string]interface{}, error) { return map[string]interface{}{ "method": ctx.Method(), "path": ctx.Path(), }, nil }, } app.Use(opa.New(cfg)) app.Get("/", func(ctx fiber.Ctx) error { return ctx.SendStatus(200) }) app.Listen(":8080") } ``` -------------------------------- ### Symmetric Key Authentication Example Source: https://github.com/gofiber/contrib/blob/main/v3/paseto/README.md A full GoFiber application example demonstrating symmetric key authentication with PASETO. It includes login, token creation, and protected routes. ```go package main import ( "time" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/extractors" pasetoware "github.com/gofiber/contrib/v3/paseto" ) const secretSymmetricKey = "symmetric-secret-key (size = 32)" func main() { app := fiber.New() // Login route app.Post("/login", login) // Unauthenticated route app.Get("/", accessible) // Paseto Middleware with local (encrypted) token apiGroup := app.Group("api", pasetoware.New(pasetoware.Config{ SymmetricKey: []byte(secretSymmetricKey), Extractor: extractors.FromAuthHeader("Bearer"), })) // Restricted Routes apiGroup.Get("/restricted", restricted) err := app.Listen(":8088") if err != nil { return } } func login(c fiber.Ctx) error { user := c.FormValue("user") pass := c.FormValue("pass") // Throws Unauthorized error if user != "john" || pass != "doe" { return c.SendStatus(fiber.StatusUnauthorized) } // Create token and encrypt it encryptedToken, err := pasetoware.CreateToken([]byte(secretSymmetricKey), user, 12*time.Hour, pasetoware.PurposeLocal) if err != nil { return c.SendStatus(fiber.StatusInternalServerError) } return c.JSON(fiber.Map{"token": encryptedToken}) } func accessible(c fiber.Ctx) error { return c.SendString("Accessible") } func restricted(c fiber.Ctx) error { payload := pasetoware.FromContext(c).(string) return c.SendString("Welcome " + payload) } ``` -------------------------------- ### Install Fiber I18n Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/i18n/README.md Install the Fiber framework and the I18n contrib module using go get. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/i18n ``` -------------------------------- ### Install New Relic Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/newrelic/README.md Install the Fiber framework and the New Relic contrib package using go get. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/newrelic ``` -------------------------------- ### Basic WebSocket Server Setup Source: https://github.com/gofiber/contrib/blob/main/v3/websocket/README.md Sets up a basic WebSocket server that echoes messages back to the client. It includes middleware to check for WebSocket upgrades and a handler for individual connections. ```go package main import ( "log" "github.com/gofiber/fiber/v3" "github.com/gofiber/contrib/v3/websocket" ) func main() { app := fiber.New() app.Use("/ws", 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 }) app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) { // c.Locals is added to the *websocket.Conn log.Println(c.Locals("allowed")) // true log.Println(c.Params("id")) // 123 log.Println(c.Query("v")) // 1.0 log.Println(c.Cookies("session")) // "" // websocket.Conn bindings https://pkg.go.dev/github.com/fasthttp/websocket?tab=doc#pkg-index var ( mt int msg []byte err error ) for { if mt, msg, err = c.ReadMessage(); err != nil { log.Println("read:", err) break } log.Printf("recv: %s", msg) if err = c.WriteMessage(mt, msg); err != nil { log.Println("write:", err) break } } })) log.Fatal(app.Listen(":3000")) // Access the websocket server: ws://localhost:3000/ws/123?v=1.0 // https://www.websocket.org/echo.html } ``` -------------------------------- ### ContainerService Start Method Source: https://github.com/gofiber/contrib/blob/main/v3/testcontainers/README.md Starts the container by calling the configured run function with the specified image and options. Implements the fiber.Service interface. ```go // Start creates and starts the container, calling the [run] function with the [img] and [opts] arguments. // It implements the [fiber.Service] interface. func (c *ContainerService[T]) Start(ctx context.Context) error ``` -------------------------------- ### Install Fgprof Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/fgprof/README.md Install the fgprof middleware and Fiber v3 using go get. Ensure you are using compatible Go versions. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/fgprof ``` -------------------------------- ### Install LoadShed Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/loadshed/README.md Install the LoadShed middleware for Fiber v3 using go get. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/loadshed ``` -------------------------------- ### Install PASETO Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/paseto/README.md Install the PASETO middleware and its dependencies for Fiber v3. ```go go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/paseto go get -u github.com/o1egl/paseto ``` -------------------------------- ### Install HCaptcha Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/hcaptcha/README.md Install the Fiber v3 framework and the HCaptcha contrib middleware using go get. ```shell go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/hcaptcha ``` -------------------------------- ### Install OPA Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/opa/README.md Install the OPA middleware for Fiber v3. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/opa ``` -------------------------------- ### Install Sentry Middleware for Fiber Source: https://github.com/gofiber/contrib/blob/main/v3/sentry/README.md Install the necessary Fiber, Sentry contrib, and Sentry Go SDK packages using go get. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/sentry go get -u github.com/getsentry/sentry-go ``` -------------------------------- ### Install WebSocket Event Helper Source: https://github.com/gofiber/contrib/blob/main/v3/websocket/event/README.md Install the Fiber WebSocket module, which includes the event subpackage. ```sh go get -u github.com/gofiber/contrib/v3/websocket ``` -------------------------------- ### Install Fiber Zap Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/zap/README.md Install the necessary Fiber and Zap packages for integration. Ensure you are using Fiber v3. ```bash go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/zap go get -u go.uber.org/zap ``` -------------------------------- ### Install Casbin Middleware and Dependencies Source: https://github.com/gofiber/contrib/blob/main/v3/casbin/README.md Installs the Casbin middleware for Fiber and a sample database adapter. ```sh go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/casbin ``` ```sh go get -u github.com/casbin/xorm-adapter ``` -------------------------------- ### PASETO Middleware with Public/Private Key Authentication Source: https://github.com/gofiber/contrib/blob/main/v3/paseto/README.md This example demonstrates setting up the PASETO middleware with Ed25519 public and private keys for signing and verifying tokens. It includes routes for login, an accessible public route, and a restricted route protected by the PASETO middleware. ```go package main import ( "crypto/ed25519" "encoding/hex" "time" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/extractors" pasetoware "github.com/gofiber/contrib/v3/paseto" ) const privateKeySeed = "e9c67fe2433aa4110caf029eba70df2c822cad226b6300ead3dcae443ac3810f" var seed, _ = hex.DecodeString(privateKeySeed) var privateKey = ed25519.NewKeyFromSeed(seed) type customPayloadStruct struct { Name string `json:"name"` ExpiresAt time.Time `json:"expiresAt"` } func main() { app := fiber.New() // Login route app.Post("/login", login) // Unauthenticated route app.Get("/", accessible) // Paseto Middleware with public (signed) token apiGroup := app.Group("api", pasetoware.New(pasetoware.Config{ Extractor: extractors.FromAuthHeader("Bearer"), PrivateKey: privateKey, PublicKey: privateKey.Public(), })) // Restricted Routes apiGroup.Get("/restricted", restricted) err := app.Listen(":8088") if err != nil { return } } func login(c fiber.Ctx) error { user := c.FormValue("user") pass := c.FormValue("pass") // Throws Unauthorized error if user != "john" || pass != "doe" { return c.SendStatus(fiber.StatusUnauthorized) } // Create token and sign it signedToken, err := pasetoware.CreateToken(privateKey, user, 12*time.Hour, pasetoware.PurposePublic) if err != nil { return c.SendStatus(fiber.StatusInternalServerError) } return c.JSON(fiber.Map{"token": signedToken}) } func accessible(c fiber.Ctx) error { return c.SendString("Accessible") } func restricted(c fiber.Ctx) error { payload := pasetoware.FromContext(c).(string) return c.SendString("Welcome " + payload) } ``` -------------------------------- ### Full Websocket Event Server Example Source: https://github.com/gofiber/contrib/blob/main/v3/websocket/event/README.md A complete Go Fiber application demonstrating websocket event handling. It sets up a basic server, registers an event listener for incoming messages to echo them back, and handles websocket upgrades with parameter extraction. ```go package main import ( "log" "github.com/gofiber/contrib/v3/websocket" "github.com/gofiber/contrib/v3/websocket/event" "github.com/gofiber/fiber/v3" ) func main() { app := fiber.New() app.Use("/ws", func(c fiber.Ctx) error { if websocket.IsWebSocketUpgrade(c) { return c.Next() } return fiber.ErrUpgradeRequired }) event.On(event.EventMessage, func(ep *event.EventPayload) { ep.Kws.Emit([]byte("echo: "+string(ep.Data)), event.TextMessage) }) app.Get("/ws/:id", event.New(func(kws *event.Websocket) { // kws.Params / kws.Locals / kws.Query / kws.Cookies wrap the Fiber // request context captured at upgrade time. kws.SetAttribute("user_id", kws.Params("id")) })) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### Basic Zerolog Middleware Setup Source: https://github.com/gofiber/contrib/blob/main/v3/zerolog/README.md Integrates Zerolog logging into a GoFiber application. Requires Zerolog and GoFiber packages. Initializes a logger and applies it using the middleware configuration. ```go package main import ( "os" middleware "github.com/gofiber/contrib/v3/zerolog" "github.com/gofiber/fiber/v3" "github.com/rs/zerolog" ) func main() { app := fiber.New() logger := zerolog.New(os.Stderr).With().Timestamp().Logger() app.Use(middleware.New(middleware.Config{ Logger: &logger, })) app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello, World!") }) if err := app.Listen(":3000"); err != nil { logger.Fatal().Err(err).Msg("Fiber app error") } } ``` -------------------------------- ### Install JWT Middleware and JWT Library Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Install the necessary packages for using the JWT middleware with Fiber and the Go JWT library. ```bash go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/jwt go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Initialize Sentry and Fiber App with Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/sentry/README.md This snippet shows the complete setup for a Fiber application, including initializing the Sentry SDK and applying the Sentry middleware. It demonstrates how to access the Sentry Hub within request handlers and middleware to add custom tags and capture messages. ```go package main import ( "fmt" "log" sdk "github.com/getsentry/sentry-go" fiberSentry "github.com/gofiber/contrib/v3/sentry" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/utils" ) func main() { _ = sdk.Init(sdk.ClientOptions{ Dsn: "", BeforeSend: func(event *sdk.Event, hint *sdk.EventHint) *sdk.Event { if hint.Context != nil { if c, ok := hint.Context.Value(sdk.RequestContextKey).(fiber.Ctx); ok { // You have access to the original Context if it panicked fmt.Println(utils.ImmutableString(c.Hostname())) } } fmt.Println(event) return event }, Debug: true, AttachStacktrace: true, }) app := fiber.New() app.Use(fiberSentry.New(fiberSentry.Config{ Repanic: true, WaitForDelivery: true, })) enhanceSentryEvent := func(c fiber.Ctx) error { if hub := fiberSentry.GetHubFromContext(c); hub != nil { hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") } return c.Next() } app.All("/foo", enhanceSentryEvent, func(c fiber.Ctx) error { panic("y tho") }) app.All("/", func(c fiber.Ctx) error { if hub := fiberSentry.GetHubFromContext(c); hub != nil { hub.WithScope(func(scope *sdk.Scope) { scope.SetExtra("unwantedQuery", "someQueryDataMaybe") hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") }) } return c.SendStatus(fiber.StatusOK) }) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### ContainerService.Start Source: https://github.com/gofiber/contrib/blob/main/v3/testcontainers/README.md Creates and starts the container, calling the run function with the img and opts arguments. It implements the fiber.Service interface. ```APIDOC ## Start ### Description Creates and starts the container, calling the [run] function with the [img] and [opts] arguments. It implements the [fiber.Service] interface. ### Signature ```go func (c *ContainerService[T]) Start(ctx context.Context) error ``` ``` -------------------------------- ### Install Testcontainers for Fiber Source: https://github.com/gofiber/contrib/blob/main/v3/testcontainers/README.md Install the necessary packages for Testcontainers integration with Fiber v3. ```shell go get -u github.com/gofiber/fiber/v3 go get -u github.com/gofiber/contrib/v3/testcontainers ``` -------------------------------- ### RS256 JWT Authentication Example Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Demonstrates how to set up RS256 JWT authentication with Fiber. It includes routes for login, an accessible public route, and a restricted route protected by JWT middleware. Note: The private key generation in this example is for demonstration purposes only and should not be used in production. ```go package main import ( "crypto/rand" "crypto/rsa" "log" "time" "github.com/gofiber/fiber/v3" "github.com/golang-jwt/jwt/v5" jwtware "github.com/gofiber/contrib/v3/jwt" ) var ( // Obviously, this is just a test example. Do not do this in production. // In production, you would have the private key and public key pair generated // in advance. NEVER add a private key to any GitHub repo. privateKey *rsa.PrivateKey ) func main() { app := fiber.New() // Just as a demo, generate a new private/public key pair on each run. See note above. rng := rand.Reader var err error privateKey, err = rsa.GenerateKey(rng, 2048) if err != nil { log.Fatalf("rsa.GenerateKey: %v", err) } // Login route app.Post("/login", login) // Unauthenticated route app.Get("/", accessible) // JWT Middleware app.Use(jwtware.New(jwtware.Config{ SigningKey: jwtware.SigningKey{ JWTAlg: jwtware.RS256, Key: privateKey.Public(), }, Extractor: extractors.FromAuthHeader("Bearer"), })) // Restricted Routes app.Get("/restricted", restricted) app.Listen(":3000") } func login(c fiber.Ctx) error { user := c.FormValue("user") pass := c.FormValue("pass") // Throws Unauthorized error if user != "john" || pass != "doe" { return c.SendStatus(fiber.StatusUnauthorized) } // Create the Claims claims := jwt.MapClaims{ "name": "John Doe", "admin": true, "exp": time.Now().Add(time.Hour * 72).Unix(), } // Create token token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) // Generate encoded token and send it as response. t, err := token.SignedString(privateKey) if err != nil { log.Printf("token.SignedString: %v", err) return c.SendStatus(fiber.StatusInternalServerError) } return c.JSON(fiber.Map{"token": t}) } func accessible(c fiber.Ctx) error { return c.SendString("Accessible") } func restricted(c fiber.Ctx) error { user := jwtware.FromContext(c) claims := user.Claims.(jwt.MapClaims) name := claims["name"].(string) return c.SendString("Welcome " + name) } ``` -------------------------------- ### OPA Input Data Example Source: https://github.com/gofiber/contrib/blob/main/v3/opa/README.md Example of data sent to the OPA policy engine as input. ```json { "method": "GET", "path": "/somePath", "query": { "name": ["John Doe"] }, "headers": { "Accept": "application/json", "Content-Type": "application/json" } } ``` -------------------------------- ### Go Socket.IO Server Setup Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Sets up a Go Fiber server with Socket.IO middleware, defining handlers for connection, custom events, messages, and disconnections. It manages connected clients and broadcasts messages. ```go package main import ( "encoding/json" "fmt" "log" "github.com/gofiber/contrib/v3/socketio" "github.com/gofiber/contrib/v3/websocket" "github.com/gofiber/fiber/v3" ) // 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.Printf("Connection event 1 - User: %s", ep.Kws.GetStringAttribute("user_id")) }) // Custom event handling supported socketio.On("CUSTOM_EVENT", func(ep *socketio.EventPayload) { fmt.Printf("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.Printf("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.Printf("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.Printf("Close event - User: %s", ep.Kws.GetStringAttribute("user_id")) }) // On error event socketio.On(socketio.EventError, func(ep *socketio.EventPayload) { fmt.Printf("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 newUserMsg, _ := json.Marshal(fmt.Sprintf("New user connected: %s and UUID: %s", userId, kws.UUID)) kws.Broadcast(newUserMsg, true, socketio.TextMessage) // Write welcome message. Raw text is encoded as a JSON string. welcomeMsg, _ := json.Marshal(fmt.Sprintf("Hello user: %s with UUID: %s", userId, kws.UUID)) kws.Emit(welcomeMsg, socketio.TextMessage) })) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### HS256 JWT Authentication Example Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Full example demonstrating JWT authentication using HS256. Includes login route for token generation and a restricted route protected by JWT middleware. ```go package main import ( "time" "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v3/extractors" jwtware "github.com/gofiber/contrib/v3/jwt" "github.com/golang-jwt/jwt/v5" ) func main() { app := fiber.New() // Login route app.Post("/login", login) // Unauthenticated route app.Get("/", accessible) // JWT Middleware app.Use(jwtware.New(jwtware.Config{ SigningKey: jwtware.SigningKey{Key: []byte("secret")}, Extractor: extractors.FromAuthHeader("Bearer"), })) // Restricted Routes app.Get("/restricted", restricted) app.Listen(":3000") } func login(c fiber.Ctx) error { user := c.FormValue("user") pass := c.FormValue("pass") // Throws Unauthorized error if user != "john" || pass != "doe" { return c.SendStatus(fiber.StatusUnauthorized) } // Create the Claims claims := jwt.MapClaims{ "name": "John Doe", "admin": true, "exp": time.Now().Add(time.Hour * 72).Unix(), } // Create token token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) // Generate encoded token and send it as response. t, err := token.SignedString([]byte("secret")) if err != nil { return c.SendStatus(fiber.StatusInternalServerError) } return c.JSON(fiber.Map{"token": t}) } func accessible(c fiber.Ctx) error { return c.SendString("Accessible") } func restricted(c fiber.Ctx) error { user := jwtware.FromContext(c) claims := user.Claims.(jwt.MapClaims) name := claims["name"].(string) return c.SendString("Welcome " + name) } ``` -------------------------------- ### Basic Fgprof Middleware Setup Source: https://github.com/gofiber/contrib/blob/main/v3/fgprof/README.md Integrate the fgprof middleware into your Fiber application to enable profiling. Access profiles via the /debug/fgprof endpoint. ```go package main import ( "log" "github.com/gofiber/contrib/v3/fgprof" "github.com/gofiber/fiber/v3" ) 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")) } ``` -------------------------------- ### Shut Down Fiber Example Services Source: https://github.com/gofiber/contrib/blob/main/v3/otel/example/README.md Clean up the Docker Compose services used for the GoFiber OpenTelemetry example. This stops and removes the containers. ```sh docker-compose down ``` -------------------------------- ### Configure Socket.IO Globals Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Override package-level variables to control timing and limits for the Engine.IO/Socket.IO transport. This example sets a custom PingInterval and PingTimeout, and increases the MaxPayload size. ```go func init() { socketio.PingInterval = 15 * time.Second socketio.PingTimeout = 10 * time.Second socketio.MaxPayload = 4 << 20 // 4 MiB } ``` -------------------------------- ### Basic i18n Setup and Usage in Fiber Source: https://github.com/gofiber/contrib/blob/main/v3/i18n/README.md This snippet demonstrates how to initialize the i18n translator with a root path for language files, specify accepted languages, and set a default language. It then shows how to use the translator to localize messages within Fiber route handlers, including handling errors and localizing messages with dynamic data. ```go package main import ( "log" contribi18n "github.com/gofiber/contrib/v3/i18n" "github.com/gofiber/fiber/v3" goi18n "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) func main() { translator := contribi18n.New(&contribi18n.Config{ RootPath: "./example/localize", AcceptLanguages: []language.Tag{language.Chinese, language.English}, DefaultLanguage: language.Chinese, }) app := fiber.New() app.Get("/", func(c fiber.Ctx) error { localize, err := translator.Localize(c, "welcome") if err != nil { return c.Status(fiber.StatusInternalServerError).SendString(err.Error()) } return c.SendString(localize) }) app.Get("/:name", func(ctx fiber.Ctx) error { return ctx.SendString(translator.MustLocalize(ctx, &goi18n.LocalizeConfig{ MessageID: "welcomeWithName", TemplateData: map[string]string{ "name": ctx.Params("name"), }, })) }) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### Circuit Breaker with Custom Metrics and Logging Source: https://github.com/gofiber/contrib/blob/main/v3/circuitbreaker/README.md Integrate Prometheus metrics and structured logging to monitor the circuit breaker's state. This example shows logging when the circuit opens and incrementing a Prometheus counter. ```go cb := circuitbreaker.New(circuitbreaker.Config{ FailureThreshold: 5, Timeout: 10 * time.Second, OnOpen: func(c fiber.Ctx) error { log.Println("Circuit Breaker Opened!") prometheus.Inc("circuit_breaker_open_count") return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{"error": "Service Down"}) }, }) ``` -------------------------------- ### Trace ID Response Header Example Source: https://github.com/gofiber/contrib/blob/main/v3/otel/README.md Demonstrates how to configure the OTel middleware to include the current trace ID in a response header, making it easy to correlate logs and traces. ```APIDOC ## Trace ID Response Header You can optionally expose the current trace ID in a dedicated response header: ```go app.Use(fiberotel.Middleware( fiberotel.WithTraceResponseHeader("X-Trace-Id"), )) ``` ``` -------------------------------- ### Go Fiber with OpenTelemetry Middleware Source: https://github.com/gofiber/contrib/blob/main/v3/otel/README.md This Go code sets up a Fiber application with OpenTelemetry tracing enabled. It initializes a tracer provider that exports traces to stdout and uses the fiberotel middleware to automatically instrument incoming requests. It also includes example routes for handling errors and retrieving user data, with tracing for the getUser function. ```Go package main import ( "context" "errors" "log" "go.opentelemetry.io/otel/sdk/resource" "github.com/gofiber/fiber/v3" fiberotel "github.com/gofiber/contrib/v3/otel" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.39.0" oteltrace "go.opentelemetry.io/otel/trace" ) var tracer = otel.Tracer("fiber-server") func main() { tp := initTracer() defer func() { if err := tp.Shutdown(context.Background()); err != nil { log.Printf("Error shutting down tracer provider: %v", err) } }() app := fiber.New() app.Use(fiberotel.Middleware()) app.Get("/error", func(ctx fiber.Ctx) error { return errors.New("abc") }) app.Get("/users/:id", func(c fiber.Ctx) error { id := c.Params("id") name := getUser(c.Context(), id) return c.JSON(fiber.Map{"id": id, "name": name}) }) log.Fatal(app.Listen(":3000")) } func initTracer() *sdktrace.TracerProvider { exporter, err := stdout.New(stdout.WithPrettyPrint()) if err != nil { log.Fatal(err) } tp := sdktrace.NewTracerProvider( sdktrace.WithSampler(sdktrace.AlwaysSample()), sdktrace.WithBatcher(exporter), sdktrace.WithResource( resource.NewWithAttributes( semconv.SchemaURL, semconv.ServiceNameKey.String("my-service"), )), ) otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})) return tp } func getUser(ctx context.Context, id string) string { _, span := tracer.Start(ctx, "getUser", oteltrace.WithAttributes(attribute.String("id", id))) defer span.End() if id == "123" { return "otel tester" } return "unknown" } ``` -------------------------------- ### Emit Named Event with Multiple Arguments Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Emits a named event with multiple arguments. Example: EmitArgs("greet", []byte(`"hi"`), []byte(`{"id":1}`)). ```go func (kws *Websocket) EmitArgs(event string, args ...[]byte) ``` -------------------------------- ### Basic Monitor Middleware Usage Source: https://github.com/gofiber/contrib/blob/main/v3/monitor/README.md Initialize the Monitor middleware with default configuration and assign it to the /metrics route. ```go package main import ( "log" "github.com/gofiber/fiber/v3" "github.com/gofiber/contrib/v3/monitor" ) func main() { app := fiber.New() // Initialize default config (Assign the middleware to /metrics) app.Get("/metrics", monitor.New()) // Or extend your config for customization // Assign the middleware to /metrics // and change the Title to `MyService Metrics Page` app.Get("/metrics", monitor.New(monitor.Config{Title: "MyService Metrics Page"})) log.Fatal(app.Listen(":3000")) } ``` -------------------------------- ### Migration from TokenPrefix to Extractor Source: https://github.com/gofiber/contrib/blob/main/v3/paseto/README.md Demonstrates how to migrate from the older TokenPrefix configuration to the new Extractor configuration using `extractors.FromAuthHeader`. ```go // Old way pasetoware.New(pasetoware.Config{ SymmetricKey: []byte("secret"), TokenPrefix: "Bearer", }) // New way pasetoware.New(pasetoware.Config{ SymmetricKey: []byte("secret"), Extractor: extractors.FromAuthHeader("Bearer"), }) ``` -------------------------------- ### Get Connection UUID Source: https://github.com/gofiber/contrib/blob/main/v3/websocket/event/README.md Retrieves the unique identifier for the current WebSocket connection. ```go func (kws *Websocket) GetUUID() string ``` -------------------------------- ### Get Connection Attribute Source: https://github.com/gofiber/contrib/blob/main/v3/websocket/event/README.md Retrieves an attribute previously set on the current WebSocket connection. ```go func (kws *Websocket) GetAttribute(key string) interface{} ``` -------------------------------- ### Basic Swaggo Usage Source: https://github.com/gofiber/contrib/blob/main/v3/swaggo/README.md Mount the Swagger UI at the /swagger/* route using the default configuration. ```go package main import ( "github.com/gofiber/fiber/v3" swaggo "github.com/gofiber/contrib/v3/swaggo" // docs are generated by Swag CLI, you have to import them. // Replace with your own docs folder, usually "github.com/username/reponame/docs". _ "github.com/username/reponame/docs" ) func main() { app := fiber.New() // Mount the UI with the default configuration under /swagger app.Get("/swagger/*", swaggo.HandlerDefault) app.Listen(":8080") } ``` -------------------------------- ### New Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Initializes a new Socket.IO instance. It takes a callback function that will be executed with a Websocket object and accepts optional websocket configuration. ```APIDOC ## New ### Description Initializes a new Socket.IO instance. It takes a callback function that will be executed with a Websocket object and accepts optional websocket configuration. ### Signature ```go func New(callback func(kws *Websocket), config ...websocket.Config) func(fiber.Ctx) error ``` ``` -------------------------------- ### Enable Polling and Mount Handler Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Enable polling on the server-side and mount the Socket.IO handler for both GET and POST requests. ```go socketio.EnablePolling = true h := socketio.New(func(kws *socketio.Websocket) { /* ... */ }) app.Get("/ws", h) app.Post("/ws", h) // Optionally allow CORS preflight: // app.Options("/ws", h) ``` -------------------------------- ### HS256 Restricted Resource Response Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Example response from a restricted resource after successful JWT authentication. The response includes a personalized welcome message. ```text Welcome John Doe ``` -------------------------------- ### HS256 Login Response Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Example JSON response containing the JWT after a successful login. This token should be stored and used in subsequent authenticated requests. ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NjE5NTcxMzZ9.RB3arc4-OyzASAaUhC2W3ReWaXAt_z2Fd3BN4aWTgEY" } ``` -------------------------------- ### Get Handshake Authentication Payload Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Retrieves the raw JSON authentication payload sent by the client during the handshake. Returns nil if no payload was provided. ```go func (kws *Websocket) HandshakeAuth() json.RawMessage ``` -------------------------------- ### Using the Legacy Event Bus Surface Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/legacy/README.md This snippet demonstrates how to use the re-exported event-bus surface from the legacy shim, including emitting a 'pong' response. ```go legacy.On(legacy.EventMessage, func(ep *legacy.EventPayload) { ep.Kws.Emit([]byte("pong"), legacy.TextMessage) }) app.Get("/ws", legacy.New(func(kws *legacy.Websocket) {})) ``` -------------------------------- ### HS256 Login Request Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Example of how to log in using form data to obtain a JWT. This is typically used to authenticate a user and issue a token for subsequent requests. ```bash curl --data "user=john&pass=doe" http://localhost:3000/login ``` -------------------------------- ### HS256 Restricted Resource Request Source: https://github.com/gofiber/contrib/blob/main/v3/jwt/README.md Example of requesting a protected resource using the JWT obtained from the login response. The token is sent in the Authorization header with the 'Bearer' scheme. ```bash curl localhost:3000/restricted -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NjE5NTcxMzZ9.RB3arc4-OyzASAaUhC2W3ReWaXAt_z2Fd3BN4aWTgEY" ``` -------------------------------- ### Use Swagger UI with Program Data Content Source: https://github.com/gofiber/contrib/blob/main/v3/swaggerui/README.md Provide Swagger content directly using FileContent instead of reading from a file path. ```go cfg := swaggerui.Config{ BasePath: "/", FilePath: "./docs/swagger.json", FileContent: mySwaggerByteSlice, Path: "swagger", Title: "Swagger API Docs", } app.Use(swaggerui.New(cfg)) ``` -------------------------------- ### Initialize Socket.IO Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/README.md Initializes a new Socket.IO instance within a Fiber callback. It expects a callback function that takes a *Websocket object and optional websocket configuration. ```go func New(callback func(kws *Websocket), config ...websocket.Config) func(fiber.Ctx) error ``` -------------------------------- ### Use Swagger UI with Custom Configuration Source: https://github.com/gofiber/contrib/blob/main/v3/swaggerui/README.md Configure the Swagger UI middleware with custom settings for BasePath, FilePath, Path, and Title. ```go cfg := swaggerui.Config{ BasePath: "/", FilePath: "./docs/swagger.json", Path: "swagger", Title: "Swagger API Docs", } app.Use(swaggerui.New(cfg)) ``` -------------------------------- ### Monitor Middleware Initialization Source: https://github.com/gofiber/contrib/blob/main/v3/monitor/README.md This snippet shows how to initialize the Monitor middleware with its default configuration and assign it to a route. It also demonstrates how to customize the configuration, such as changing the page title. ```APIDOC ## Initialize Monitor Middleware ### Description Initializes the Monitor middleware for a Fiber application. This middleware provides a web-based dashboard to monitor server metrics. ### Method `monitor.New(config ...monitor.Config) fiber.Handler` ### Parameters - `config` (*monitor.Config) - Optional - A configuration struct to customize the middleware's behavior. ### Config Options - **Title** (`string`) - Metrics page title. Default: `Fiber Monitor`. - **Refresh** (`time.Duration`) - Refresh period. Default: `3 seconds`. - **APIOnly** (`bool`) - Whether the service should expose only the monitoring API. Default: `false`. - **Next** (`func(c fiber.Ctx) bool`) - Define a function to skip this middleware when returned true. Default: `nil`. - **CustomHead** (`string`) - Custom HTML code to Head Section (Before End). Default: `empty`. - **FontURL** (`string`) - FontURL for specific font resource path or URL. Default: `https://fonts.googleapis.com/css2?family=Roboto:wght@400;900&display=swap`. - **ChartJsURL** (`string`) - ChartJsURL for specific chartjs library, path or URL. Default: `https://cdn.jsdelivr.net/npm/chart.js@2.9/dist/Chart.bundle.min.js`. ### Request Example ```go // Default configuration app.Get("/metrics", monitor.New()) // Custom configuration app.Get("/metrics", monitor.New(monitor.Config{Title: "MyService Metrics Page"})) ``` ### Response - `fiber.Handler` - A Fiber handler function that can be used in Fiber routes. ``` -------------------------------- ### Preferred Import for New Code Source: https://github.com/gofiber/contrib/blob/main/v3/socketio/legacy/README.md Use this import path for new applications requiring WebSocket event bus functionality. ```go import "github.com/gofiber/contrib/v3/websocket/event" ``` -------------------------------- ### Circuit Breaker with Failure Count Reset Interval Source: https://github.com/gofiber/contrib/blob/main/v3/circuitbreaker/README.md Configure an interval to reset the failure count in the closed state. Failures reported after this interval elapses will start a new count, preventing indefinite accumulation. ```go cb := circuitbreaker.New(circuitbreaker.Config{ FailureThreshold: 5, Timeout: 10 * time.Second, Interval: 30 * time.Second, // Reset failure count every 30 seconds }) app.Use(circuitbreaker.Middleware(cb)) ``` -------------------------------- ### LoadShed with Custom Rejection Handler Source: https://github.com/gofiber/contrib/blob/main/v3/loadshed/README.md Configure LoadShed middleware with a custom OnShed handler to define specific responses for rejected requests based on HTTP method. This allows for differentiated error handling for GET requests versus others. ```go package main import ( "time" "github.com/gofiber/fiber/v3" loadshed "github.com/gofiber/contrib/v3/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{}, }, OnShed: func(ctx fiber.Ctx) error { if ctx.Method() == fiber.MethodGet { return ctx. Status(fiber.StatusTooManyRequests). Send([]byte{}) } return ctx. Status(fiber.StatusTooManyRequests). JSON(fiber.Map{ "error": "Keep calm", }) }, })) app.Get("/", func(c fiber.Ctx) error { return c.SendString("Welcome!") }) app.Listen(":3000") } ```