Go Fiber 한글 공식 문서
  • 🙇‍♀️안녕하세요
  • 🏠Home
    • 👋Welcome
    • 📁API
      • 📦Fiber
      • 🚀App
      • 🧠Ctx
      • 📋Constants
      • 🌎Client
      • 📃Log
      • 🧬Middleware
        • Adaptor
        • BasicAuth
        • Cache
        • Compress
        • CORS
        • CSRF
        • EarlyData
        • Encrypt Cookie
        • EnvVar
        • ETag
        • ExpVar
        • Favicon
        • FileSystem
        • Health Check
        • Helmet
        • Idempotency
        • Keyauth
        • Limiter
        • Logger
        • Monitor
        • Pprof
        • Proxy
        • Recover
        • Redirect
        • RequestID
        • Rewrite
        • Session
        • Skip
        • Timeout
    • 📁Guide
      • 🔌Routing
      • 🎭Grouping
      • 📝Templates
      • 🐛Error Handling
      • 🔎Validation
      • 🎣Hooks
      • ⚡Make Fiber Faster
    • 📁Extra
      • 🤔FAQ
      • 📊Benchmarks
  • 🧩Extra
    • 🧬Contrip
      • 👋Welcome
      • Casbin
      • Fgprof
      • Fiberi18n
      • Fibernewrelic
      • Fibersentry
      • Fiberzap
      • Fiberzerolog
      • JWT
      • LoadShed
      • Opafiber
      • Otelfiber
        • Example
      • Paseto
      • README
      • Swagger
      • Websocket
    • 📦Storage
      • 👋Welcome
      • ArangoDB
      • Azure Blob
      • Badger
      • Bbolt
      • Coherence
      • Couchbase
      • DynamoDB
      • Etcd
      • Memcache
      • Memory
      • Minio
      • MongoDB
      • MSSQL
      • MySQL
      • Nats
      • Pebble
      • Postgres
      • Redis
      • Ristretto
      • Rueidis
      • S3
      • ScyllaDb
      • SQLite3
    • 📃Template
      • 👋Welcome
      • Ace
      • Amber
      • Django
      • Handlebars
      • HTML
        • Golang Templates Cheatsheet
      • Jet
      • Mustache
      • Pug
      • Slim
Powered by GitBook
On this page
  • Constants
  • OnRoute
  • OnName
  • OnGroup
  • OnGroupName
  • OnListen
  • OnFork
  • OnShutdown
  • OnMount
  1. Home
  2. Guide

Hooks


Fiber v2.30.0 부터, 몇몇 메서드를 실행할 때 사용자 정의 함수를 실행할 수 있습니다. 다음은 이러한 hooks의 목록입니다:

  • OnRoute

  • OnName

  • OnGroup

  • OnGroupName

  • OnListen

  • OnFork

  • OnShutdown

  • OnMount

Constants

// Handlers define a function 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 OnShutdownHandler = func() error
type OnMountHandler = func(*App) error

OnRoute

OnRoute는 각 route 등록 시 사용자 함수를 실행하는 hook입니다. 또한 route 파라미터를 통해 route 속성을 가져올 수 있습니다.

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

OnName

OnName은 각 route 이름 지정 시 사용자 함수를 실행하는 hook입니다. 또한 route 파라미터를 통해 route 속성을 가져올 수 있습니다.

OnName은 그룹이 아닌 route 이름 지정에서만 작동합니다.

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

import (
	"fmt"

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

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은 각 그룹 등록 시 사용자 함수를 실행하는 hook입니다. 또한 group 파라미터를 통해 group 속성을 가져올 수 있습니다.

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

OnGroupName

OnGroupName은 각 그룹 이름 지정 시 사용자 함수를 실행하는 hook입니다. 또한 group 파라미터를 통해 group 속성을 가져올 수 있습니다.

OnGroupName은 route가 아닌 그룹 이름 지정에서만 작동합니다.

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

OnListen

OnListen은 Listen, ListenTLS, Listener에서 사용자 함수를 실행하는 hook입니다.

func (h *Hooks) OnListen(handler ...OnListenHandler)
app := fiber.New(fiber.Config{
  DisableStartupMessage: true,
})

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

app.Listen(":5000")

OnFork

OnFork는 Fork에서 사용자 함수를 실행하는 hook입니다.

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

OnShutdown

OnShutdown은 Shutdown 이후에 사용자 함수를 실행하는 hook입니다.

func (h *Hooks) OnShutdown(handler ...OnShutdownHandler)  

OnMount

OnMount는 마운팅 과정 이후에 사용자 함수를 실행하는 hook입니다. 하위 앱이 상위 앱에 마운트될 때 mount 이벤트가 발생합니다. 상위 앱은 파라미터로 전달됩니다. app과 group 마운팅에 모두 작동합니다.

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

import (
	"fmt"

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

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

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

		return nil
	})

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

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

OnName/OnRoute/OnGroup/OnGroupName hooks는 마운트에 민감합니다. 하위 앱 중 하나에서 이러한 route를 사용하고 마운트하면, route와 그룹의 경로는 마운트 접두사로 시작됩니다.

PreviousValidationNextMake Fiber Faster

Last updated 1 year ago

🏠
📁
🎣