Hooks
A Hook is a pieces of functional that gets executed either before handling the request or after.
Hooks are located in the directory hooks/
in the root directory of the project.
A Hook in Goffee is simply a function
of type core.Hook
that gets assigned to routes so that it can be executed before or after the execution of the request's controller.
A Hook to be executed before processing the request
In case the logic gets defined before
calling the function c.Next()
. Below an example of a hook to executed before processing the request
package hooks
import (
"fmt"
"git.smarteching.com/goffee/core"
)
var myHook core.Hook = func(c *core.Context) {
// Logic goes here ...
c.Next()
}
To assign this hook myHook
to a specific route, simply pass it as a third parameter to the route's definition, check this code below for more info:
controller.Get("/", controllers.Login, hooks.myHook)
A Hook to be executed after processing the request
In case the logic gets defined after
calling the function c.Next()
. Below an example of a hook to be executed after processing the request
package hooks
import (
"fmt"
"git.smarteching.com/goffee/core"
)
var myHook core.Hook = func(c *core.Context) {
c.Next()
// Logic goes here ...
}
To assign this hook myHook
to a specific route, simply pass it as a third parameter to the route's definition, check the code below:
router.Get("/", controllers.Login, hooks.myHook)
Assigning multiple hooks to routes
You can simply pass them as a second
, third
, fourth
, etc; parameters to the route's definition, regardless of the hook been a before request handling hook
or an after request handling hook
, here is how:
controller.Get("/",
controllers.Login,
hooks.myHook1,
hooks.myHook2,
hooks.myHook3
)
Return response from the hook
Sometimes you might want to return the response to users from the hook, you can achieve that by simply calling the function ForceSendResponse()
on the Response
property on the context object.
package hooks
import (
"git.smarteching.com/goffee/core"
)
var UnauthorizedCheck core.Hook = func(c *core.Context) {
// Logic goes here ...
c.Response.
SetStatusCode(401).
SetContentType("text/html").
HTML("<h1>unauthorized.</h1>").
ForceSendResponse()
c.Next()
}
Registering a hook globally to all routes
You can register hooks globally in the file /register-global-hooks.go
in the root directory of the project.
Simply pass the hook as an argument to the function core.UseHook(your-hook)
, here is how:
package main
import (
"git.smarteching.com/goffee/core"
"git.smarteching.com/goffee/[my-project]/hooks"
)
func registerGlobalHooks() {
//########################################
//# Global middlewares registration #####
//########################################
// Register global middlewares here ...
core.UseHook(hooks.HandleNotFound)
core.UseHook(hooks.ExampleHook)
}
Note
Always remember to call c.Next()
function in your hooks in the right place