Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Revel interceptor


May 15, 2021 Revel


Table of contents


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:

  • Request a record
  • Error handling
  • The state remains

In Revel, there are two forms of interceptors:

  1. Function Interceptor: Please refer to InterceptorFunc interface.

    • You cannot hook up to a specific controller method
    • Can be applied to all, any controller
  2. Method Interceptor: One without parameters and returns a revel.Result controller method

    • Only controller methods can be intercepted
    • The called controller can be modified

The order in which the interceptor is executed is related to where it was added

Intercept time

There are four intercept times that can be registered over the life of a request:

  1. BEFORE: Intercepts are performed after the request is routed and the session, flash, parameter is resolved, and the controller method is called.
  2. AFTER: Intercepts before the request returns a result, but the result is applied. If a panic appears, the intercept is not called.
  3. PANIC: Intercepted after a panic exit occurs in the controller method or when the results are applied.
  4. FINAL: Intercepted after the controller method is executed and the result is applied.

Results

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:

  1. BEFORE: No further interceptors were called, nor was it a controller method.
  2. AFTER: All interceptors can still run.
  3. PANIC: All interceptors can still run.
  4. FINAL: All interceptors can still run.

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.

For example

Function interceptor

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 interceptor

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)
}