May 15, 2021 Revel
An interceptor is a function that is called before or after the framework executes a method. It allows aspect-oriented programming to work as follows:
In Revel, there are two forms of interceptors:
Function Interceptor: Please refer to
InterceptorFunc
interface.
Method Interceptor: One without parameters and returns a
revel.Result
controller method
The order in which the interceptor is executed is related to where it was added
There are four intercept times that can be registered over the life of a request:
Interceptors typically return
nil
which case the request needs to continue processing and cannot be interrupted.
Return a
nil
revel.Result
of Result, depending on when the interceptor is called:
In any case, the returned results are attached to any existing results:
BEFORE: The result returned is guaranteed to be final.
AFTER: It may be a further interceptor that can return its own results.
Here is a simple example of defining and registering function interceptors.
func checkUser(c *revel.Controller) revel.Result {
if user := connected(c); user == nil {
c.Flash.Error("请先登录")
return c.Redirect(App.Index)
}
return nil
}
func init() {
revel.InterceptFunc(checkUser, revel.BEFORE, &Hotels{})
}
Method interceptors have two ways to sign:
func (c AppController) example() revel.Result
func (c *AppController) example() revel.Result
Here's the same example, with only one controller intercepted.
func (c Hotels) checkUser() revel.Result {
if user := connected(c); user == nil {
c.Flash.Error("请先登录")
return c.Redirect(App.Index)
}
return nil
}
func init() {
revel.InterceptMethod(Hotels.checkUser, revel.BEFORE)
}