fiber/docs/api/hooks.md
JIeJaitt 4b62d3d592
🔥 feat: Improve and Optimize ShutdownWithContext Func (#3162)
* feat: Optimize ShutdownWithContext method in app.go

- Reorder mutex lock acquisition to the start of the function
- Early return if server is not running
- Use defer for executing shutdown hooks
- Simplify nil check for hooks
- Remove TODO comment

This commit improves the readability, robustness, and execution order
of the shutdown process. It ensures consistent state throughout the
shutdown and guarantees hook execution even in error cases.

* feat: Enhance ShutdownWithContext test for improved reliability

- Add shutdown hook verification
- Implement better synchronization with channels
- Improve error handling and assertions
- Adjust timeouts for more consistent results
- Add server state check after shutdown attempt
- Include comments explaining expected behavior

This commit improves the comprehensiveness and reliability of the
ShutdownWithContext test, ensuring proper verification of shutdown
hooks, timeout behavior, and server state during long-running requests.

* 📚 Doc: update the docs to explain shutdown & hook execution order

* 🩹 Fix: Possible Data Race on shutdownHookCalled Variable

* 🩹 Fix: Remove the default Case

* 🩹 Fix: Import sync/atomic

* 🩹 Fix: golangci-lint problem

* 🎨 Style: add block in api.md

* 🩹 Fix: go mod tidy

* feat: Optimize ShutdownWithContext method in app.go

- Reorder mutex lock acquisition to the start of the function
- Early return if server is not running
- Use defer for executing shutdown hooks
- Simplify nil check for hooks
- Remove TODO comment

This commit improves the readability, robustness, and execution order
of the shutdown process. It ensures consistent state throughout the
shutdown and guarantees hook execution even in error cases.

* feat: Enhance ShutdownWithContext test for improved reliability

- Add shutdown hook verification
- Implement better synchronization with channels
- Improve error handling and assertions
- Adjust timeouts for more consistent results
- Add server state check after shutdown attempt
- Include comments explaining expected behavior

This commit improves the comprehensiveness and reliability of the
ShutdownWithContext test, ensuring proper verification of shutdown
hooks, timeout behavior, and server state during long-running requests.

* 📚 Doc: update the docs to explain shutdown & hook execution order

* 🩹 Fix: Possible Data Race on shutdownHookCalled Variable

* 🩹 Fix: Remove the default Case

* 🩹 Fix: Import sync/atomic

* 🩹 Fix: golangci-lint problem

* 🎨 Style: add block in api.md

* 🩹 Fix: go mod tidy

* ♻️ Refactor: replaced OnShutdown  by OnPreShutdown and OnPostShutdown

* ♻️ Refactor: streamline post-shutdown hook execution in graceful shutdown process

* 🚨 Test: add test for gracefulShutdown

* 🔥 Feature: Using executeOnPreShutdownHooks and executeOnPostShutdownHooks Instead of OnShutdownSuccess and OnShutdownError

* 🩹 Fix: deal Listener err

* 🩹 Fix: go lint error

* 🩹 Fix: reduced memory alignment

* 🩹 Fix: reduced memory alignment

* 🩹 Fix: context should be created inside the concatenation.

* 📚 Doc: update what_new.md and hooks.md

* ♻️ Refactor: use blocking channel instead of time.Sleep

* 🩹 Fix: Improve synchronization in error propagation test.

* 🩹 Fix: Replace sleep with proper synchronization.

* 🩹 Fix: Server but not shut down properly

* 🩹 Fix: Using channels to synchronize and pass results

* 🩹 Fix: timeout with long running request

* 📚 Doc: remove OnShutdownError and OnShutdownSuccess from fiber.md

* Update hooks.md

* 🚨 Test: Add graceful shutdown timeout error test case

* 📝 Doc: Restructure hooks documentation for OnPreShutdown and OnPostShutdown

* 📝 Doc: Remove extra whitespace in hooks documentation

---------

Co-authored-by: yingjie.huang <yingjie.huang@fosunhn.net>
Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
2025-02-22 17:32:51 +01:00

5.3 KiB

id, title, sidebar_position
id title sidebar_position
hooks 🎣 Hooks 7

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

With Fiber you can execute custom user functions at specific method execution points. Here is a list of these hooks:

Constants

// Handlers define functions to create hooks for Fiber.
type OnRouteHandler = func(Route) error
type OnNameHandler = OnRouteHandler
type OnGroupHandler = func(Group) error
type OnGroupNameHandler = OnGroupHandler
type OnListenHandler = func(ListenData) error
type OnForkHandler = func(int) error
type OnPreShutdownHandler  = func() error
type OnPostShutdownHandler = func(error) error
type OnMountHandler = func(*App) error

OnRoute

OnRoute is a hook to execute user functions on each route registration. You can access route properties via the route parameter.

func (h *Hooks) OnRoute(handler ...OnRouteHandler)

OnName

OnName is a hook to execute user functions on each route naming. You can access route properties via the route parameter.

:::caution OnName only works with named routes, not groups. :::

func (h *Hooks) OnName(handler ...OnNameHandler)
package main

import (
    "fmt"

    "github.com/gofiber/fiber/v3"
)

func main() {
    app := fiber.New()

    app.Get("/", func(c fiber.Ctx) error {
        return c.SendString(c.Route().Name)
    }).Name("index")

    app.Hooks().OnName(func(r fiber.Route) error {
        fmt.Print("Name: " + r.Name + ", ")
        return nil
    })

    app.Hooks().OnName(func(r fiber.Route) error {
        fmt.Print("Method: " + r.Method + "\n")
        return nil
    })

    app.Get("/add/user", func(c fiber.Ctx) error {
        return c.SendString(c.Route().Name)
    }).Name("addUser")

    app.Delete("/destroy/user", func(c fiber.Ctx) error {
        return c.SendString(c.Route().Name)
    }).Name("destroyUser")

    app.Listen(":5000")
}

// Results:
// Name: addUser, Method: GET
// Name: destroyUser, Method: DELETE

OnGroup

OnGroup is a hook to execute user functions on each group registration. You can access group properties via the group parameter.

func (h *Hooks) OnGroup(handler ...OnGroupHandler)

OnGroupName

OnGroupName is a hook to execute user functions on each group naming. You can access group properties via the group parameter.

:::caution OnGroupName only works with named groups, not routes. :::

func (h *Hooks) OnGroupName(handler ...OnGroupNameHandler)

OnListen

OnListen is a hook to execute user functions on Listen, ListenTLS, and Listener.

func (h *Hooks) OnListen(handler ...OnListenHandler)
package main

import (
    "log"
    "os"

    "github.com/gofiber/fiber/v3"
    "github.com/gofiber/fiber/v3/log"
)

func main() {
    app := fiber.New(fiber.Config{
        DisableStartupMessage: true,
    })

    app.Hooks().OnListen(func(listenData fiber.ListenData) error {
        if fiber.IsChild() {
            return nil
        }
        scheme := "http"
        if listenData.TLS {
            scheme = "https"
        }
        log.Println(scheme + "://" + listenData.Host + ":" + listenData.Port)
        return nil
    })

    app.Listen(":5000")
}

OnFork

OnFork is a hook to execute user functions on fork.

func (h *Hooks) OnFork(handler ...OnForkHandler)

OnPreShutdown

OnPreShutdown is a hook to execute user functions before shutdown.

func (h *Hooks) OnPreShutdown(handler ...OnPreShutdownHandler)

OnPostShutdown

OnPostShutdown is a hook to execute user functions after shutdown.

func (h *Hooks) OnPostShutdown(handler ...OnPostShutdownHandler)

OnMount

OnMount is a hook to execute user functions after the mounting process. The mount event is fired when a sub-app is mounted on a parent app. The parent app is passed as a parameter. It works for both app and group mounting.

func (h *Hooks) OnMount(handler ...OnMountHandler)
package main

import (
    "fmt"

    "github.com/gofiber/fiber/v3"
)

func main() {
    app := fiber.New()
    app.Get("/", testSimpleHandler).Name("x")

    subApp := fiber.New()
    subApp.Get("/test", testSimpleHandler)

    subApp.Hooks().OnMount(func(parent *fiber.App) error {
        fmt.Print("Mount path of parent app: " + parent.MountPath())
        // Additional custom logic...
        return nil
    })

    app.Mount("/sub", subApp)
}

func testSimpleHandler(c fiber.Ctx) error {
    return c.SendString("Hello, Fiber!")
}

// Result:
// Mount path of parent app: /sub

:::caution OnName/OnRoute/OnGroup/OnGroupName hooks are mount-sensitive. If you use one of these routes on sub app, and you mount it; paths of routes and groups will start with mount prefix.