http_dispatch.pl -- Dispatch requests in the HTTP server
Most code doesn't need to use this directly; instead use library(http/http_server), which combines this library with the typical HTTP libraries that most servers need.
This module can be placed between http_wrapper.pl and the application code to associate HTTP locations to predicates that serve the pages. In addition, it associates parameters with locations that deal with timeout handling and user authentication. The typical setup is:
server(Port, Options) :- http_server(http_dispatch, [ port(Port) | Options ]). :- http_handler('/index.html', write_index, []). write_index(Request) :- ...
- http_handler(+Path, :Closure, +Options) is det
- Register Closure as a handler for HTTP requests. Path is either an
absolute path such as
'/home.html'
or a term Alias(Relative). Where Alias is associated with a concrete path using http:location/3 and resolved using http_absolute_location/3. Relative can be a single atom or a term `Segment1/Segment2/...`, where each element is either an atom or a variable. If a segment is a variable it matches any segment and the binding may be passed to the closure. If the last segment is a variable it may match multiple segments. This allows registering REST paths, for example::- http_handler(root(user/User), user(Method, User), [ method(Method), methods([get,post,put]) ]). user(get, User, Request) :- ... user(post, User, Request) :- ...
If an HTTP request arrives at the server that matches Path, Closure is called as below, where Request is the parsed HTTP request.
call(Closure, Request)
Options is a list containing the following options:
- authentication(+Type)
- Demand authentication. Authentication methods are pluggable. The
library http_authenticate.pl provides a plugin for user/password
based
Basic
HTTP authentication. - chunked
- Use
Transfer-encoding: chunked
if the client allows for it. - condition(:Goal)
- If present, the handler is ignored if Goal does not succeed.
- content_type(+Term)
- Specifies the content-type of the reply. This value is currently not used by this library. It enhances the reflexive capabilities of this library through http_current_handler/3.
- id(+Atom)
- Identifier of the handler. The default identifier is the predicate name. Used by http_location_by_id/2 and http_link_to_id/3.
- hide_children(+Bool)
- If
true
on a prefix-handler (see prefix), possible children are masked. This can be used to (temporary) overrule part of the tree. - method(+Method)
- Declare that the handler processes Method. This is equivalent to
methods([Method])
. Usingmethod(*)
allows for all methods. - methods(+ListOfMethods)
- Declare that the handler processes all of the given methods. If this option appears multiple times, the methods are combined.
- prefix
- Call Pred on any location that is a specialisation of Path. If
multiple handlers match, the one with the longest path is used.
Options defined with a prefix handler are the default options
for paths that start with this prefix. Note that the handler
acts as a fallback handler for the tree below it:
:- http_handler(/, http_404([index('index.html')]), [spawn(my_pool),prefix]).
- priority(+Integer)
- If two handlers handle the same path, the one with the highest priority is used. If equal, the last registered is used. Please be aware that the order of clauses in multifile predicates can change due to reloading files. The default priority is 0 (zero).
- spawn(+SpawnOptions)
- Run the handler in a separate thread. If SpawnOptions is an atom, it is interpreted as a thread pool name (see create_thread_pool/3). Otherwise the options are passed to http_spawn/2 and from there to thread_create/3. These options are typically used to set the stack limits.
- time_limit(+Spec)
- One of
infinite
,default
or a positive number (seconds). Ifdefault
, the value from the settinghttp:time_limit
is taken. The default of this setting is 300 (5 minutes). See setting/2.
Note that http_handler/3 is normally invoked as a directive and processed using term-expansion. Using term-expansion ensures proper update through make/0 when the specification is modified.
- http_delete_handler(+Spec) is det
- Delete handler for Spec. Typically, this should only be used for
handlers that are registered dynamically. Spec is one of:
- id(Id)
- Delete a handler with the given id. The default id is the handler-predicate-name.
- path(Path)
- Delete handler that serves the given path.
- next_generation is det[private]
- current_generation(-G) is det[private]
- Increment the generation count.
- compile_handler(+Path, :Pred, +Options, -Clause) is det[private]
- Compile a handler specification.
- combine_methods(+OptionsIn, -Options) is det[private]
- Combine
method(M)
andmethods(MList)
options into a singlemethods(MList)
option. - check_path(+PathSpecIn, -PathSpecOut, -Options) is det[private]
- Validate the given path specification. We want one of
- AbsoluteLocation
- Alias(Relative)
Similar to absolute_file_name/3, Relative can be a term
Component/Component/...
. Relative may be a/
separated list of path segments, some of which may be variables. A variable patches any segment and its binding can be passed to the handler. If such a pattern is found Options is unified with[segment_pattern(SegmentList)]
. - http_dispatch(Request) is det
- Dispatch a Request using http_handler/3 registrations. It performs
the following steps:
- Find a matching handler based on the
path
member of Request. If multiple handlers match due to theprefix
option or variables in path segments (see http_handler/3), the longest specification is used. If multiple specifications of equal length match the one with the highest priority is used. - Check that the handler matches the
method
member of the Request or throwpermission_error(http_method, Method, Location)
- Expand the request using expansion hooks registered by
http_request_expansion/3. This may add fields to the request,
such the authenticated user, parsed parameters, etc. The
hooks may also throw exceptions, notably using http_redirect/3
or by throwing
http_reply(Term, ExtraHeader, Context)
exceptions. - Extract possible fields from the Request using e.g.
method(Method)
as one of the options. - Call the registered closure, optionally spawning the request to a new thread or enforcing a time limit.
- Find a matching handler based on the
- http_request_expansion(:Goal, +Rank:number)
- Register Goal for expanding the HTTP request handler. Goal is called
as below. If Goal fail the request is passed to the next expansion
unmodified.
call(Goal, Request0, Request, Options)
If multiple goals are registered they expand the request in a pipeline starting with the expansion hook with the lowest rank.
Besides rewriting the request, for example by validating the user identity based on HTTP authentication or cookies and adding this to the request, the hook may raise HTTP exceptions to indicate a bad request, permission error, etc. See http_status_reply/4.
Initially, auth_expansion/3 is registered with rank
100
to deal with the older http:authenticate/3 hook. - expand_request(+Request0, -Request, +Options)[private]
- Expand an HTTP request. Options is a list of combined options provided with the handler registration (see http_handler/3).
- http_current_handler(+Location, :Closure) is semidet
- http_current_handler(-Location, :Closure) is nondet
- True if Location is handled by Closure.
- http_current_handler(+Location, :Closure, -Options) is semidet
- http_current_handler(?Location, :Closure, ?Options) is nondet
- Resolve the current handler and options to execute it.
- http_location_by_id(+ID, -Location) is det
- True when Location represents the HTTP path to which the handler
with identifier ID is bound. Handler identifiers are deduced from
the http_handler/3 declaration as follows:
- Explicit id
-
If a term
id(ID)
appears in the option list of the handler, ID it is used and takes preference over using the predicate. - Using the handler predicate
-
ID matches a handler if the predicate name matches ID. The
ID may have a module qualification, e.g.,
Module:Pred
If the handler is declared with a pattern, e.g.,
root(user/User)
, the location to access a particular user may be accessed using e.g.,user('Bob')
. The number of arguments to the compound term must match the number of variables in the path pattern.A plain atom ID can be used to find a handler with a pattern. The returned location is the path up to the first variable, e.g.,
/user/
in the example above.User code is adviced to use http_link_to_id/3 which can also add query parameters to the URL. This predicate is a helper for http_link_to_id/3.
- http_link_to_id(+HandleID, +Parameters, -HREF)
- HREF is a link on the local server to a handler with given ID,
passing the given Parameters. This predicate is typically used
to formulate a HREF that resolves to a handler implementing a
particular predicate. The code below provides a typical example.
The predicate user_details/1 returns a page with details about a
user from a given id. This predicate is registered as a handler.
The DCG user_link//1 renders a link to a user, displaying the
name and calling user_details/1 when clicked. Note that the
location (
root(user_details)
) is irrelevant in this equation and HTTP locations can thus be moved freely without breaking this code fragment.:- http_handler(root(user_details), user_details, []). user_details(Request) :- http_parameters(Request, [ user_id(ID) ]), ... user_link(ID) --> { user_name(ID, Name), http_link_to_id(user_details, [id(ID)], HREF) }, html(a([class(user), href(HREF)], Name)).
- http_reload_with_parameters(+Request, +Parameters, -HREF) is det
- Create a request on the current handler with replaced search parameters.
- authentication(+Options, +Request, -Fields) is det[private]
- Verify authentication information. If authentication is requested through Options, demand it. The actual verification is done by the multifile predicate http:authenticate/3. The library http_authenticate.pl provides an implementation thereof.
- auth_expansion(+Request0, -Request, +Options) is semidet[private]
- Connect the HTTP authentication infrastructure by means of http_request_expansion/2.
- find_handler(+Path, -Action, -Options) is det[private]
- Find the handler to call from Path. Rules:
- If there is a matching handler, use this.
- If there are multiple
prefix(Path)
handlers, use the longest.
If there is a handler for
/dir/
and the requested path is/dir
, find_handler/3 throws a http_reply exception, causing the wrapper to generate a 301 (Moved Permanently) reply. - supports_method(+Request, +Options) is det[private]
- Verify that the asked http method is supported by the handler. If not, raise an error that will be mapped to a 405 page by the http wrapper.
- action(+Action, +Request, +Options) is det[private]
- Execute the action found. Here we take care of the options
time_limit
,chunked
andspawn
. - call_action(+Action, +Request, +Options)[private]
- http_reply_file(+FileSpec, +Options, +Request) is det
- Options is a list of
- cache(+Boolean)
- If
true
(default), handle If-modified-since and send modification time. - mime_type(+Type)
- Overrule mime-type guessing from the filename as provided by file_mime_type/2.
- static_gzip(+Boolean)
- If true (default
false
) and, in addition to the plain file, there is a.gz
file that is not older than the plain file and the client accepsgzip
encoding, send the compressed file withTransfer-encoding: gzip
. - unsafe(+Boolean)
- If
false
(default), validate that FileSpec does not contain references to parent directories. E.g., specifications such aswww('../../etc/passwd')
are not allowed. - headers(+List)
- Provides additional reply-header fields, encoded as a list of Field(Value).
If caching is not disabled, it processes the request headers
If-modified-since
andRange
. - http_safe_file(+FileSpec, +Options) is det
- True if FileSpec is considered safe. If it is an atom, it
cannot be absolute and cannot have references to parent
directories. If it is of the form
alias(Sub)
, than Sub cannot have references to parent directories. - http_redirect(+How, +To, +Request) is det
- Redirect to a new location. The argument order, using the
Request as last argument, allows for calling this directly from
the handler declaration:
:- http_handler(root(.), http_redirect(moved, myapp('index.html')), []).
- http_404(+Options, +Request) is det
- Reply using an "HTTP 404 not found" page. This handler is
intended as fallback handler for prefix handlers. Options
processed are:
- index(Location)
- If there is no path-info, redirect the request to Location using http_redirect/3.
- http_switch_protocol(:Goal, +Options)
- Send an
"HTTP 101 Switching Protocols"
reply. After sending the reply, the HTTP library callscall(Goal, InStream, OutStream)
, where InStream and OutStream are the raw streams to the HTTP client. This allows the communication to continue using an an alternative protocol.If Goal fails or throws an exception, the streams are closed by the server. Otherwise Goal is responsible for closing the streams. Note that Goal runs in the HTTP handler thread. Typically, the handler should be registered using the
spawn
option if http_handler/3 or Goal must call thread_create/3 to allow the HTTP worker to return to the worker pool.The streams use binary (octet) encoding and have their I/O timeout set to the server timeout (default 60 seconds). The predicate set_stream/2 can be used to change the encoding, change or cancel the timeout.
This predicate interacts with the server library by throwing an exception.
The following options are supported:
- header(+Headers)
- Backward compatible. Use
headers(+Headers)
. - headers(+Headers)
- Additional headers send with the reply. Each header takes the form Name(Value).
- path_tree(-Tree) is det[private]
- Compile paths into a tree. The treee is multi-rooted and
represented as a list of nodes, where each node has the form:
node(PathOrPrefix, Action, Options, Children)
The tree is a potentially complicated structure. It is cached in a global variable. Note that this cache is per-thread, so each worker thread holds a copy of the tree. If handler facts are changed the generation is incremented using next_generation/0 and each worker thread will re-compute the tree on the next ocasion.
- prefix_tree(PrefixList, +Tree0, -Tree)[private]
- prefix_options(+PrefixTree, +DefOptions, -OptionTree)[private]
- Generate the option-tree for all prefix declarations.
- add_paths_tree(+OPTree, -Tree) is det[private]
- Add the plain paths.
- plain_path(-Path, -Action, -Options) is nondet[private]
- True if {Path,Action,Options} is registered and Path is a plain (i.e. not prefix) location.
- add_path_tree(+Path, +Action, +Options, +Tree0, -Tree) is det[private]
- Add a path to a tree. If a handler for the same path is already defined, the one with the highest priority or the latest takes precedence.