Starting with ZXTM 5.0, TrafficScriptTM has gained the ability to create new subroutines to reduce code duplication inside a TrafficScript rule.
For example:
sub securityerror( $url )
{
log.error( $url . " failed a security check from " .
request.getremoteip() );
http.sendresponse( "403 Permission denied", "text/html",
"Permission Denied", "" );
}
if( request.getremoteip() == "1.2.3.4" ) {
securityerror( http.getrawurl() );
} else if( string.startswith( http.getpath(), "/secure" ) ) {
securityerror( http.getrawurl() );
}
Data can be returned from a subroutine using the 'return' statement, additionally $1 -> $9 are available as global variables.
When using subroutines there are some points to be aware of:
- Variables (except $1 -> $9) are local to the subroutine, so arguments should be used to pass data to a subroutine.
- The subroutine can be declared anywhere in the TrafficScript rule, there is no need to declare it before it is used.
- The number of arguments is always checked at compile time so calling subroutines will never cause a run time error.
- Subroutines can, of course, call other subroutines (or themselves!).