The Chicago Boss API is mostly stable, but still might change before 1.0.

Jump to:   Routes   Authorization   Return values   Caching   Content-Language   Post-processing   SimpleBridge request object

Chicago Boss associates each URL with a function of a controller. The URL /foo/bar will call the function foo_controller:bar. Each controller module should go into your project's src/controller/ directory and the file name should start with the application name and end with "_controller.erl", e.g. "appname_my_controller.erl". Helper functions should go into your project's src/lib/ directory. Controllers can take one parameter or two parameters: the SimpleBridge request object, and an optional session ID (if sessions are enabled). Declare it like:

-module(appname_my_controller, [Req]).

Or:

-module(appname_my_controller, [Req, SessionID]).

Each exported controller function takes two or three arguments:

Example function clauses:

% GET /blog/view
view('GET', []) ->
    ...
% GET /blog/view/1234
view('GET', [Id]) ->
    ...
% GET /blog/view/tag/funny
view('GET', ["tag", Tag]) ->
    ...
% GET /blog/view/tag/funny/author/saint-paul
view('GET', ["tag", Tag, "author", AuthorName]) ->
    ...
% GET /blog/view/2009/08
view('GET', [Year, Month]) ->
    ...

These function clauses act as templates for constructing URLs in the view; for each CamelCase variable, simply use the lower-cased underscored equivalent as the parameter name. To continue the example above, you can construct URLs to match the above controllers with the following view tags:

{% url action="view" %}
{% url action="view" id="1234" %}
{% url action="view" tag="funny" %}
{% url action="view" tag="funny" author_name="saint-paul" %}
{% url action="view" year="2009" month="08" %}

Template variables can of course be used in place of string literals.

Routes

Most routing takes place in the controller pattern-matching code. You can define additional routes in priv/my_application.routes. The file contains a list of erlang terms, one per line finished with a dot. Each term is a tuple with a URL or an HTTP status code as the first term, and a Location::proplist() as the second term.

The Location proplist must contain keys for controller and action. An optional application key will route requests across applications.

A few examples of routes:

{"/", [{controller, "main"}, {action, "welcome"}]}.
{"/signup", [{application, login_app}, {controller, "account"}, {action, "create"}]}.
{404, [{controller, "main"}, {action, "not_found"}]}.

Most routes directly render the specified action; however, routing across applications (as in the second example) results in a 302 redirect. Note that the {% url %} template tag will use the routes file to generate "pretty" URLs where appropriate.

Additional Location parameters will be matched against the variable names of the controller's token list. For example, if user_controller.erl contains:

profile('GET', [UserId]) -> ...

Then the location [{controller, "user"}, {action, "profile"}, {user_id, "123"}] will invoke the "profile" action of user_controller and pass in "123" as the only token (that is, UserId). If a location parameter does not match any variables in the token list, it will be passed in as a query parameter (e.g. ?user_id=123).

Routing URLs may contain regular expresssions. For example, the following route will match all URLs that start with a digit:

{"/[0-9].*", [...]}.

Sub-expressions can be captured using parentheses and substituted with the atoms '$1', '$2', etc. For example, the following route will capture a string of digits and pass them in as the coupon_id parameter:

{"/([0-9]+)", [{controller, "coupon"}, {action, "redeem"}, {coupon_id, '$1'}]}.

Alternatively, named groups may be used to identify captured sub-expressions. For example, the following route is equivalent to the one above:

{"/(?<id>[0-9]+)", [{controller, "coupon"}, {action, "redeem"}, {coupon_id, '$id'}]}.

The route expressions must match the entire URL. That is, the expressions are implicitly bookended with ^ and $.

To define a default action for a controller, simply add a default_action attribute to the controller like so:

-default_action(index).

Authorization

If an action takes three arguments, then the function before_/3 in your controller will be passed:

  1. the action name as a string
  2. the request method as an atom
  3. the list of URL tokens

before_/3 should return one of:

{ok, ExtraInfo}

ExtraInfo will be passed as the third argument to the action, and as a variable called "_before" to the templates.

{redirect, Location}

Location = string() | [{Key::atom(), Value::atom()}]

Do not execute the action. Instead, perform a 302 redirect to Location, which can be a string or a proplist that will be converted to a URL using the routes system.

Probably most common before_/3 looks like:

before_(_, _, _) ->
    my_user_lib:require_login(Req).

Which might return a tuple of user credential or else redirect to a login page. This way, if you want to require a login to a set of actions, just give those actions a User argument, and the actions will be login protected and have access to the User variable.


Return values

Whether or not it takes a third argument, a controller action should return with one of the following:

ok

The template will be rendered without any variables.

{ok, Variables::proplist()}

Variables will be passed into the associated Django template.

{ok, Variables::proplist(), Headers::proplist()}

Variables will be passed into the associated Django template, and Headers are HTTP headers you want to set (e.g., Content-Type).

js

The template will be rendered without any variables and served as Content-Type: application/javascript.

{js, Variables::proplist()}

Variables will be passed into the associated Django template and the result will be served as Content-Type: application/javascript.

{js, Variables::proplist(), Headers::proplist()}

Variables will be passed into the associated Django template, the result served as Content-Type: application/javascript, and Headers are HTTP headers you want to set.

{redirect, Location}

Location = string() | [{action, Value::string()}, ...]

Perform a 302 HTTP redirect to Location, which may be a URL string or a proplist of parameters that will be converted to a URL using the routes system.

{redirect, Location, Headers::proplist()}

Perform a 302 HTTP redirect to Location and set additional HTTP Headers.

{moved, Location}

Location = string() | [{action, Value::string()}, ...]

Perform a 301 HTTP redirect to Location, which may be a URL string or a proplist of parameters that will be converted to a URL using the routes system.

{moved, Location, Headers::proplist()}

Perform a 301 HTTP redirect to Location and set additional HTTP Headers.

{action_other, OtherLocation}

OtherLocation = [{action, Value::string()}, ...]

Execute the controller action specified by OtherLocation, but without performing an HTTP redirect.

{render_other, OtherLocation}

OtherLocation = [{action, Value::string()}, ...]

Render the view from OtherLocation, but don't actually execute the associated controller action.

{render_other, OtherLocation, Variables}

Render the view from OtherLocation using Variables, but don't actually execute the associated controller action.

{output, Output::iolist()}

Skip views altogether and return Output to the client.

{output, Output::iolist(), Headers::proplist()}

Skip views altogether and return Output to the client while setting additional HTTP Headers.

{stream, Generator::function(), Acc0}

Stream a response to the client using HTTP chunked encoding. For each chunk, the Generator function is passed an accumulator (initally Acc0) and should return either {output, Data, Acc1} or done.

{stream, Generator::function(), Acc0, Headers::proplist()}

Same as above, but set additional HTTP Headers.

{json, Data::proplist()}

Return Data as a JSON object to the client. Performs appropriate serialization if the values in Data contain a BossRecord or a list of BossRecords.

{json, Data::proplist(), Headers::proplist()}

Return Data to the client as a JSON object while setting additional HTTP Headers.

{jsonp, Callback::string(), Data::proplist()}

Returns Data as a JSONP method call to the client. Performs appropriate serialization if the values in Data contain a BossRecord or a list of BossRecords.

{jsonp, Callback::string(), Data::proplist(), Headers::proplist()}

Return Data to the client as a JSONP method call (as above) while setting additional HTTP Headers.

not_found

Invoke the 404 File Not Found handler.

{StatusCode::integer(), Body::iolist(), Headers::proplist()}

Return an arbitary HTTP integer StatusCode along with a Body and additional HTTP Headers.


Caching

Caching should be a part of any scalability strategy. In addition to caching the results of database queries (see config), Chicago Boss can cache the list of variables returned from controller actions. CB can also cache entire rendered web pages, but in doing so you will lose the benefit of customizing the page contents with the _before variable, which is not cached.

To enable caching, first make sure the cache_enable is set to true in your configuration and that you've configured cache servers. At present only Memcached cache servers are supported, but additional adapters will be added in the future.

Next, define a cache_ function with the following arguments:

  1. Action - the action name (a string)
  2. Tokens - a list of tokens
  3. AuthInfo (optional) - authorization information returned from the before_ filter (see Authorization)

The cache_ function should return one of:

Finally, CacheOptions is a proplist possibly containing:

Note that separate cache entries are created for each language as returned by lang_ (see Content-Language).

Example cache_ function:

cache_("index", []) ->
    {page, [{seconds, 30}]};
cache_("profile", [ProfileId]) ->
    {vars, [{seconds, 300}, {watch, ProfileId ++ ".*"}]};
cache_(_, _) ->
    none.

Content-Language

CB application views can be multi-lingual. By default, the language served to the client is chosen by comparing the incoming Accept-Language header to the available translations in a given view (see "How Chicago Boss Chooses Which Language To Serve". This can be overridden in two ways:

  1. Returning [{"Content-Language", Lang}] from each action in your controller
  2. Defining a lang_ function in your controller which returns the chosen language

The lang_ function will be passed the name of the current action, and optionally the result of the before_ filter. This function should return one of:


Post-processing

If it exists, a function called after_ in your controller will be passed the result that is about to be returned to the client. The 'after_' function takes two or three arguments:

  1. The action name, as a string
  2. The HTTP result tuple
  3. The result of the before_ function, provided one exists

The after_ function should return a (possibly) modified HTTP result tuple. Result tuples may be one of:

{redirect, Location::string(), Headers::proplist()}

Performs a 302 HTTP redirect to Location and sets additional HTTP Headers.

{ok, Payload::iolist(), Headers::proplist()}

Returns a 200 OK response to the client with Payload as the HTTP body, and sets additional HTTP Headers.

{unauthorized, Payload::iolist(), Headers::proplist()}

Returns a 401 Unauthorized response to the client with Payload as the HTTP body, and sets additional HTTP Headers.

{not_found, Payload::iolist(), Headers::proplist()}

Returns a 404 Not Found response to the client with Payload as the HTTP body, and sets additional HTTP Headers.

{error, Payload::iolist(), Headers::proplist()}

Returns a 500 Internal Error response to the client with Payload as the HTTP body, and sets additional HTTP Headers.


SimpleBridge

Controller functions are passed a SimpleBridge request object (slightly modified for Boss's purposes). Useful functions in the request object include:

request_method() -> atom()

Get the request method, e.g. GET, POST, etc.

protocol() -> http | https

Get the request protocol (HTTP or HTTPS).

peer_ip() -> tuple()

Get the IP Address of the connected client as a 4-tuple for IPv4 or an 8-tuple for IPv6 (e.g. {127, 0, 0, 1})

query_param( Key::string() ) -> string() | undefined
query_param( Key::string(), DefaultValue::term() ) -> string() | Default Value

Get the value of a given query string parameter (e.g. "?id=1234")

post_param( Key::string() ) -> string() | undefined
post_param( Key::string(), DefaultValue::term() ) -> string() | Default Value

Get the value of a given POST parameter.

param( Key::string() ) -> string() | undefined
param( Key::string(), DefaultValue::term() ) -> string() | Default Value

Get the value of a given POST/GET parameter.

deep_post_param( [ Path::string() ] ) -> DeepParam | undefined

Get the value of a given "deep" POST parameter. This function parses parameters that have numerical or labeled indices, such as "widget[4][name]", and returns either a value or a set of nested lists (for numerical indices) and proplists (for string indices).

header( Header::string() | atom() ) -> string() | undefined

Get the value of a given HTTP request header. Valid Header values are strings or one of these atoms:

cookie( Key::string() ) -> string() | undefined

Get the value of a given cookie.