Subroutines are declared in TrafficScript using the sub keyword as follows:
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
Variables in TrafficScript subroutines are local, with the exception of $1 to $9 which can be used as global variables.
Subroutines can be declared anywhere in a TrafficScript rule (they do not need to be declared before they are referenced) and subroutines can call other subroutines:
sub factorial( $n ) { if( $n == 0 ) return 1; return $n*factorial( $n-1 ); }
Subroutines can be defined in one TrafficScript rule (colloquially named a 'library') and imported into another rule using the 'import' or 'import as' syntax:
TrafficScript 'library' ResourceTable:
# TrafficScript library ResourceTable # Looks up key-value pair in external resource file sub lookup( $filename, $key ) { $contents = resource.get( $filename ); if( string.regexmatch( $contents, '\n'.$key.'\s+([^\n]+)' ) ) return $1; if( string.regexmatch( $contents, '^'.$key.'\s+([^\n]+)' ) ) return $1; return ""; }
Another rule can reference the 'lookup' function in the ResourceTable library:
import ResourceTable as table; $status = table.lookup( "auth.txt", $user );