% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\subsection{library(http/http_dispatch): Dispatch requests in the HTTP server}

\label{sec:httpdispatch}

This module can be placed between \file{http_wrapper.pl} and the application
code to associate HTTP \textit{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:

\begin{code}
server(Port, Options) :-
        http_server(http_dispatch,
                    [ port(Port)
                    | Options
                    ]).

:- http_handler('/index.html', write_index, []).

write_index(Request) :-
        ...
\end{code}

\vspace{0.7cm}

\begin{description}
    \predicate[det]{http_handler}{3}{+Path, :Closure, +Options}
Register \arg{Closure} as a handler for HTTP requests. \arg{Path} is either an
absolute path such as \verb$'/home.html'$ or a term Alias(Relative).
Where Alias is associated with a concrete path using \qpredref{http}{location}{3}
and resolved using \predref{http_absolute_location}{3}. \arg{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:

\begin{code}
:- http_handler(root(user/User), user(Method, User),
                [ method(Method),
                  methods([get,port,put])
                ]).

user(get, User, Request) :-
    ...
user(post, User, Request) :-
    ...
\end{code}

If an HTTP request arrives at the server that matches \arg{Path}, \arg{Closure}
is called as below, where \arg{Request} is the parsed HTTP request.

\begin{code}
call(Closure, Request)
\end{code}

\arg{Options} is a list containing the following options:

\begin{description}
    \termitem{authentication}{+Type}
Demand authentication. Authentication methods are pluggable. The
library \file{http_authenticate.pl} provides a plugin for user/password
based \verb$Basic$ HTTP authentication.
    \termitem{chunked}{}
Use \verb$Transfer-encoding: chunked$ if the client allows for it.
    \termitem{condition}{:Goal}
If present, the handler is ignored if \arg{Goal} does not succeed.
    \termitem{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 \predref{http_current_handler}{3}.
    \termitem{id}{+Term}
Identifier of the handler. The default identifier is the
predicate name. Used by \predref{http_location_by_id}{2}.
    \termitem{hide_children}{+Bool}
If \const{true} on a prefix-handler (see prefix), possible children
are masked. This can be used to (temporary) overrule part of the
tree.
    \termitem{method}{+Method}
Declare that the handler processes \arg{Method}. This is equivalent to
\verb$methods([Method])$. Using \verb$method(*)$ allows for all methods.
    \termitem{methods}{+ListOfMethods}
Declare that the handler processes all of the given methods. If
this option appears multiple times, the methods are combined.
    \termitem{prefix}{}
Call Pred on any location that is a specialisation of \arg{Path}. If
multiple handlers match, the one with the longest path is used.
\arg{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:

\begin{code}
:- http_handler(/, http_404([index('index.html')]),
                [spawn(my_pool),prefix]).
\end{code}

    \termitem{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).
    \termitem{spawn}{+SpawnOptions}
Run the handler in a seperate thread. If \arg{SpawnOptions} is an
atom, it is interpreted as a thread pool name (see
\predref{create_thread_pool}{3}). Otherwise the options are passed to
\predref{http_spawn}{2} and from there to \predref{thread_create}{3}. These options
are typically used to set the stack limits.
    \termitem{time_limit}{+Spec}
One of \const{infinite}, \const{default} or a positive number (seconds). If
\const{default}, the value from the setting \verb$http:time_limit$ is
taken. The default of this setting is 300 (5 minutes). See
\predref{setting}{2}.
\end{description}

Note that \predref{http_handler}{3} is normally invoked as a directive and
processed using term-expansion. Using term-expansion ensures proper
update through \predref{make}{0} when the specification is modified. We do not
expand when the cross-referencer is running to ensure proper
handling of the meta-call.

\begin{tags}
\mtag{Errors}- \verb$existence_error(http_location, Location)$ \\- \verb$permission_error(http_method, Method, Location)$
    \tag{See also}
\predref{http_reply_file}{3} and \predref{http_redirect}{3} are generic
handlers to serve files and achieve redirects.
\end{tags}

    \predicate[det]{http_delete_handler}{1}{+Spec}
Delete handler for \arg{Spec}. Typically, this should only be used for
handlers that are registered dynamically. \arg{Spec} is one of:

\begin{description}
    \termitem{id}{Id}
Delete a handler with the given id. The default id is the
handler-predicate-name.
    \termitem{path}{Path}
Delete handler that serves the given path.
\end{description}

    \predicate[det]{http_dispatch}{1}{Request}
Dispatch a \arg{Request} using \predref{http_handler}{3} registrations. It performs
the following steps:

\begin{enumerate}
    \item Find a matching handler based on the \const{path} member of \arg{Request}.
If multiple handlers match due to the \const{prefix} option or
variables in path segments (see \predref{http_handler}{3}), the longest
specification is used. If multiple specifications of equal
length match the one with the highest priority is used.
    \item Check that the handler matches the \const{method} member of the
\arg{Request} or throw \verb$permission_error(http_method, Method, Location)$
    \item Expand the request using expansion hooks registered by
\predref{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 \predref{http_redirect}{3}
or by throwing \verb$http_reply(Term, ExtraHeader, Context)$
exceptions.
    \item Extract possible fields from the \arg{Request} using e.g.
\verb$method(Method)$ as one of the options.
    \item Call the registered \textit{closure}, optionally spawning the
request to a new thread or enforcing a time limit.
\end{enumerate}

    \predicate{http_request_expansion}{2}{:Goal, +Rank:number}
Register \arg{Goal} for expanding the HTTP request handler. \arg{Goal} is called
as below. If \arg{Goal} fail the request is passed to the next expansion
unmodified.

\begin{code}
call(Goal, Request0, Request, Options)
\end{code}

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 \predref{http_status_reply}{4}.

Initially, \predref{auth_expansion}{3} is registered with rank \verb$100$ to deal
with the older \qpredref{http}{authenticate}{3} hook.

    \predicate[semidet]{http_current_handler}{2}{+Location, :Closure}
\nodescription
    \predicate[nondet]{http_current_handler}{2}{-Location, :Closure}
True if \arg{Location} is handled by \arg{Closure}.

    \predicate[semidet]{http_current_handler}{3}{+Location, :Closure, -Options}
\nodescription
    \predicate[nondet]{http_current_handler}{3}{?Location, :Closure, ?Options}
Resolve the current handler and options to execute it.

    \predicate[det]{http_location_by_id}{2}{+ID, -Location}
Find the HTTP \arg{Location} of handler with \arg{ID}. If the setting (see
\predref{setting}{2}) http:prefix is active, \arg{Location} is the handler
location prefixed with the prefix setting. Handler IDs can be
specified in two ways:

\begin{description}
    \termitem{id}{ID}
If this appears in the option list of the handler, this
it is used and takes preference over using the predicate.
    \infixtermitem{\Smodule}{\arg{M}}{\arg{PredName}}
The module-qualified name of the predicate.
    \termitem{\arg{PredName}}{}
The unqualified name of the predicate.
\end{description}

\begin{tags}
    \tag{Errors}
\verb$existence_error(http_handler_id, Id)$.
    \tag{deprecated}
The predicate \predref{http_link_to_id}{3} provides the same
functionality with the option to add query parameters or a
path parameter.
\end{tags}

    \predicate{http_link_to_id}{3}{+HandleID, +Parameters, -HREF}
\arg{HREF} is a link on the local server to a handler with given ID,
passing the given \arg{Parameters}. This predicate is typically used
to formulate a \arg{HREF} that resolves to a handler implementing a
particular predicate. The code below provides a typical example.
The predicate \predref{user_details}{1} returns a page with details about a
user from a given id. This predicate is registered as a handler.
The DCG \dcgref{user_link}{1} renders a link to a user, displaying the
name and calling \predref{user_details}{1} when clicked. Note that the
location (\verb$root(user_details)$) is irrelevant in this equation and
HTTP locations can thus be moved freely without breaking this
code fragment.

\begin{code}
:- 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)).
\end{code}

\begin{arguments}
\arg{Parameters} & is one of

\begin{itemize}
    \item \verb$path_postfix(File)$ to pass a single value as the last
segment of the HTTP location (path). This way of
passing a parameter is commonly used in REST APIs.
    \item A list of search parameters for a \verb$GET$ request.
\end{itemize}

 \\
\end{arguments}

\begin{tags}
    \tag{See also}
\predref{http_location_by_id}{2} and \predref{http_handler}{3} for defining and
specifying handler IDs.
\end{tags}

    \predicate[det]{http_reload_with_parameters}{3}{+Request, +Parameters, -HREF}
Create a request on the current handler with replaced search
parameters.

    \predicate[det]{http_reply_file}{3}{+FileSpec, +Options, +Request}
\arg{Options} is a list of

\begin{description}
    \termitem{cache}{+Boolean}
If \const{true} (default), handle If-modified-since and send
modification time.
    \termitem{mime_type}{+Type}
Overrule mime-type guessing from the filename as
provided by \predref{file_mime_type}{2}.
    \termitem{static_gzip}{+Boolean}
If true (default \const{false}) and, in addition to the plain
file, there is a \verb$.gz$ file that is not older than the
plain file and the client acceps \const{gzip} encoding, send
the compressed file with \verb$Transfer-encoding: gzip$.
    \termitem{unsafe}{+Boolean}
If \const{false} (default), validate that \arg{FileSpec} does not
contain references to parent directories. E.g.,
specifications such as \verb$www('../../etc/passwd')$ are
not allowed.
    \termitem{headers}{+List}
Provides additional reply-header fields, encoded as a
list of \textit{Field(Value)}.
\end{description}

If caching is not disabled, it processes the request headers
\verb$If-modified-since$ and \verb$Range$.

\begin{tags}
\mtag{throws}- \verb$http_reply(not_modified)$ \\- \verb$http_reply(file(MimeType, Path))$
\end{tags}

    \predicate[det]{http_safe_file}{2}{+FileSpec, +Options}
True if \arg{FileSpec} is considered \textit{safe}. If it is an atom, it
cannot be absolute and cannot have references to parent
directories. If it is of the form \verb$alias(Sub)$, than Sub cannot
have references to parent directories.

\begin{tags}
\mtag{Errors}- instantiation_error \\- \verb$permission_error(read, file, FileSpec)$
\end{tags}

    \predicate[det]{http_redirect}{3}{+How, +To, +Request}
Redirect to a new location. The argument order, using the
\arg{Request} as last argument, allows for calling this directly from
the handler declaration:

\begin{code}
:- http_handler(root(.),
                http_redirect(moved, myapp('index.html')),
                []).
\end{code}

\begin{arguments}
\arg{How} & is one of \const{moved}, \verb$moved_temporary$ or \verb$see_other$ \\
\arg{To} & is an atom, a aliased path as defined by
\predref{http_absolute_location}{3}. or a term \verb$location_by_id(Id)$. If \arg{To} is
not absolute, it is resolved relative to the current location. \\
\end{arguments}

    \predicate[det]{http_404}{2}{+Options, +Request}
Reply using an "HTTP 404 not found" page. This handler is
intended as fallback handler for \textit{prefix} handlers. \arg{Options}
processed are:

\begin{description}
    \termitem{index}{Location}
If there is no path-info, redirect the request to
\arg{Location} using \predref{http_redirect}{3}.
\end{description}

\begin{tags}
    \tag{Errors}
\verb$http_reply(not_found(Path))$
\end{tags}

    \predicate{http_switch_protocol}{2}{:Goal, +Options}
Send an \verb$"HTTP 101 Switching Protocols"$ reply. After sending
the reply, the HTTP library calls \verb$call(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 \arg{Goal} fails or throws an exception, the streams are closed by
the server. Otherwise \arg{Goal} is responsible for closing the
streams. Note that \arg{Goal} runs in the HTTP handler thread.
Typically, the handler should be registered using the \const{spawn}
option if \predref{http_handler}{3} or \arg{Goal} must call \predref{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 \predref{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:

\begin{description}
    \termitem{header}{+Headers}
Backward compatible. Use \verb$headers(+Headers)$.
    \termitem{headers}{+Headers}
Additional headers send with the reply. Each header takes the
form Name(Value).
\end{description}
\end{description}

