Skip to content

EN.03.06.Custom Routing

stormcat24 edited this page Aug 12, 2014 · 1 revision

Document of custom routing.

Use case of routing

By using Aeromock Routing DSL, be able to control custom routing. Good use case of custom routing is as follows.

  • If actual URL and template path does not match, cannot do page transition to click link. So resolve this problem by custom routing.
  • In the case of various pattern data file, want to replace _dataid parameter with different named request parameter.
  • Switch resolve template file by request domain or useragent. Like switch PC or smartphone.

routing.groovy

Create routing.groovy at project root directory. Be able to control routing by using Aeromock Routing DSL in routing.groovy.

server directive

Root element of routing DSL should be routing, define server directive in the internal. Basically it's only to be specify localhost, the same as virtual host by specifing multiple domain.

Only localhost

routing {
    server "localhost", {
        // TODO
    }
}

VirtualHost

routing {
    server "local.pc.example.com", {
        // TODO
    }

    server "local.sp.example.com", {
        // TODO
    }
}

rewrite directive

Rewrite URL matched regular expression.

  • 1st Argument: Regular expression want to match
  • 2nd Argument: Callback object has invoked when matched. Be able to get extracted string from callback argument by regular expression. Then rewrited result is evaluated string the last in callback statement.

Example

Rewrite request of /help/help-top.do to /help/top.

  • 1st Step Remove .do. Extract string expect .do by regular expression. Extracted string can be referenced from _ as callback variable. _ variable has extracted strings like _1, _2, ... _n variables. In this example, _._1 is string expect .do.
  • 2nd Step .do removed, then target string is /help/help-top, then extract top from this. 1st argument is a regular expression matches /help/help-top, be extracted top. So result of rewrite is /help/top. There is $ as variable in this string, this notation is GString of Groovy.
routing {
    server "localhost", {
        // 1st Step
        rewrite(/^(.+)\.do$/), { _ ->
            _._1
        }

        // 2nd Step
        rewrite(/^\/help\/help-([A-Z]+)/), { _ ->
            "/help/${_._1}"
        }
    }
}

Builtin Variables

In routing.groovy, be able to refer to builtin variables defined on Aeromock.

Clone this wiki locally