Beego的钩子函数 hookfunc

Yufan Feng
Jul 28, 2017 · 2 min read

通过beego.Run()入口方法我们可以看到

func Run(params ...string) {
initBeforeHTTPRun()
.....
BeeApp.Run()
}

在initBeforeHTTPRun()函数中完成了对hookfunc切片的添加,有几个系统的钩子函数,并且我们可以通过AddAPPStartFunc()添加自己的钩子函数,以便在系统初始化时完成自定义操作。

func initBeforeHTTPRun() {
//init hooks
AddAPPStartHook(registerMime)
AddAPPStartHook(registerDefaultErrorHandler)
AddAPPStartHook(registerSession)
AddAPPStartHook(registerTemplate)
AddAPPStartHook(registerAdmin)
AddAPPStartHook(registerGzip)

for _, hk := range hooks {
if err := hk(); err != nil {
panic(err)
}
}
}

例如我们在beego启动时注册一个简单的自定义打印函数,注意该函数需要是hookfunc类型,因为切片维护的是

//hook function to run
type hookfunc func() error

var (
hooks = make([]hookfunc, 0)
)

自定义钩子函数

func main() {
beego.AddAPPStartHook(myHookFunc)
beego.Run()
}

var myHookFunc = func() error {
fmt.Println("myHookFunc ......")
return nil
}

beego启动将打印

☁  hello-beego [dev] ⚡ ./main                                                                                      
myHookFunc ......
[I] [asm_amd64.s:2197] http server Running on http://:8080
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade