[not loaded]PublicShow sourcehttp_server.pl -- HTTP server library

This library combines the core server functionality provided by several libraries that are needed by almost any web server. It exports the commonly used predicates from library(http/thread_httpd), library(http/http_dispatch), library(http/http_wrapper), library(http/http_parameters), library(http/html_write), library(http/http_json), and library(http/http_dyn_workers).

Source http_server(+Options) is det
Create an HTTP server using http_dispatch/1 for handling requests. See http_server/2 and http_dispatch/1 for details.

Re-exported predicates

The following predicates are re-exported from other modules

Source http_current_server(:Goal, ?Port) is nondet
True if Goal is the goal of a server at Port.
deprecated
- Use http_server_property(Port, goal(Goal))
Source http_server_property(?Port, ?Property) is nondet
True if Property is a property of the HTTP server running at Port. Defined properties are:
goal(:Goal)
Goal used to start the server. This is often http_dispatch/1.
scheme(-Scheme)
Scheme is one of http or https.
start_time(?Time)
Time-stamp when the server was created.
Source http_server(:Goal, :Options) is det
Create a server at Port that calls Goal for each parsed request. Options provide a list of options. Defined options are
port(?Address)
Port to bind to. Address is either a port or a term Host:Port. The port may be a variable, causing the system to select a free port. See tcp_bind/2.
unix_socket(+Path)
Instead of binding to a TCP port, bind to a Unix Domain Socket at Path.
entry_page(+URI)
Affects the message printed while the server is started. Interpreted as a URI relative to the server root.
tcp_socket(+Socket)
If provided, use this socket instead of the creating one and binding it to an address. The socket must be bound to an address.
workers(+Count)
Determine the number of worker threads. Default is 5. This is fine for small scale usage. Public servers typically need a higher number.
timeout(+Seconds)
Maximum time of inactivity trying to read the request after a connection has been opened. Default is 60 seconds. See set_stream/1 using the timeout option.
keep_alive_timeout(+Seconds)
Time to keep `Keep alive' connections alive. Default is 2 seconds.
stack_limit(+Bytes)
Stack limit to use for the workers. The default is inherited from the main thread. If you need to control resource usage you may consider the spawn option of http_handler/3 and library(thread_pool).
silent(Bool)
If true (default false), do not print an informational message that the server was started.

A typical initialization for an HTTP server that uses http_dispatch/1 to relay requests to predicates is:

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).

start_server(Port) :-
    http_server(http_dispatch, [port(Port)]).

Note that multiple servers can coexist in the same Prolog process. A notable application of this is to have both an HTTP and HTTPS server, where the HTTP server redirects to the HTTPS server for handling sensitive requests.

Source http_workers(+Port, -Workers) is det
http_workers(+Port, +Workers:int) is det
Query or set the number of workers for the server at this port. The number of workers is dynamically modified. Setting it to 1 (one) can be used to profile the worker using tprofile/1.
Source http_add_worker(+Port, +Options) is det
Add a new worker to the HTTP server for port Port. Options overrule the default queue options. The following additional options are processed:
max_idle_time(+Seconds)
The created worker will automatically terminate if there is no new work within Seconds.
Source http_current_worker(?Port, ?ThreadID) is nondet
True if ThreadID is the identifier of a Prolog thread serving Port. This predicate is motivated to allow for the use of arbitrary interaction with the worker thread for development and statistics.
Source http_stop_server(+Port, +Options)
Stop the indicated HTTP server gracefully. First stops all workers, then stops the server.
To be done
- Realise non-graceful stop
Source http_spawn(:Goal, +Options) is det
Continue this connection on a new thread. A handler may call http_spawn/2 to start a new thread that continues processing the current request using Goal. The original thread returns to the worker pool for processing new requests. Options are passed to thread_create/3, except for:
pool(+Pool)
Interfaces to library(thread_pool), starting the thread on the given pool.

If a pool does not exist, this predicate calls the multifile hook http:create_pool/1 to create it. If this predicate succeeds the operation is retried.

Source 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]). Using method(*) 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). If default, the value from the setting http: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.

Errors
- existence_error(http_location, Location)
- permission_error(http_method, Method, Location)
See also
- http_reply_file/3 and http_redirect/3 are generic handlers to serve files and achieve redirects.
Source http_parameters(+Request, ?Parms) is det
Source http_parameters(+Request, ?Parms, :Options) is det
Get HTTP GET or POST form-data, applying type validation, default values, etc. Provided options are:
attribute_declarations(:Goal)
Causes the declarations for an attributed named A to be fetched using call(Goal, A, Declarations).
form_data(-Data)
Return the data read from the GET por POST request as a list Name = Value. All data, including name/value pairs used for Parms, is unified with Data.

The attribute_declarations hook allows sharing the declaration of attribute-properties between many http_parameters/3 calls. In this form, the requested attribute takes only one argument and the options are acquired by calling the hook. For example:

    ...,
    http_parameters(Request,
                    [ sex(Sex)
                    ],
                    [ attribute_declarations(http_param)
                    ]),
    ...

http_param(sex, [ oneof(male, female),
                  description('Sex of the person')
                ]).
bug
- If both request parameters (?name=value&...) and a POST are present the parameters are extracted from the request parameters. Still, as it is valid to have request parameters in a POST request this predicate should not process POST requests. We will keep the current behaviour as the it is not common for a request to have both request parameters and a POST data of the type application/x-www-form-urlencoded.

In the unlikely event this poses a problem the request may be specified as [method(get)|Request].

Source http_parameters(+Request, ?Parms) is det
Source http_parameters(+Request, ?Parms, :Options) is det
Get HTTP GET or POST form-data, applying type validation, default values, etc. Provided options are:
attribute_declarations(:Goal)
Causes the declarations for an attributed named A to be fetched using call(Goal, A, Declarations).
form_data(-Data)
Return the data read from the GET por POST request as a list Name = Value. All data, including name/value pairs used for Parms, is unified with Data.

The attribute_declarations hook allows sharing the declaration of attribute-properties between many http_parameters/3 calls. In this form, the requested attribute takes only one argument and the options are acquired by calling the hook. For example:

    ...,
    http_parameters(Request,
                    [ sex(Sex)
                    ],
                    [ attribute_declarations(http_param)
                    ]),
    ...

http_param(sex, [ oneof(male, female),
                  description('Sex of the person')
                ]).
bug
- If both request parameters (?name=value&...) and a POST are present the parameters are extracted from the request parameters. Still, as it is valid to have request parameters in a POST request this predicate should not process POST requests. We will keep the current behaviour as the it is not common for a request to have both request parameters and a POST data of the type application/x-www-form-urlencoded.

In the unlikely event this poses a problem the request may be specified as [method(get)|Request].

Source reply_html_page(:Head, :Body) is det
Source reply_html_page(+Style, :Head, :Body) is det
Provide the complete reply as required by http_wrapper.pl for a page constructed from Head and Body. The HTTP Content-type is provided by html_current_option/1.
Source html_meta(+Heads) is det
This directive can be used to declare that an HTML rendering rule takes HTML content as argument. It has two effects. It emits the appropriate meta_predicate/1 and instructs the built-in editor (PceEmacs) to provide proper colouring for the arguments. The arguments in Head are the same as for meta_predicate or can be constant html. For example:
:- html_meta
      page(html,html,?,?).
Source reply_json_dict(+JSONTerm) is det
Source reply_json_dict(+JSONTerm, +Options) is det
As reply_json/1 and reply_json/2, but assumes the new dict based data representation. Note that this is the default if the outer object is a dict. This predicate is needed to serialize a list of objects correctly and provides consistency with http_read_json_dict/2 and friends.
Source reply_json_dict(+JSONTerm) is det
Source reply_json_dict(+JSONTerm, +Options) is det
As reply_json/1 and reply_json/2, but assumes the new dict based data representation. Note that this is the default if the outer object is a dict. This predicate is needed to serialize a list of objects correctly and provides consistency with http_read_json_dict/2 and friends.
Source http_read_json_dict(+Request, -Dict) is det
Source http_read_json_dict(+Request, -Dict, +Options) is det
Similar to http_read_json/2,3, but by default uses the version 7 extended datatypes.
Source http_read_json_dict(+Request, -Dict) is det
Source http_read_json_dict(+Request, -Dict, +Options) is det
Similar to http_read_json/2,3, but by default uses the version 7 extended datatypes.
Source is_json_content_type(+ContentType) is semidet
True if ContentType is a header value (either parsed or as atom/string) that denotes a JSON value.

Undocumented predicates

The following predicates are exported, but not or incorrectly documented.

 http_dispatch(Arg1)
 http_delete_handler(Arg1)
 http_request_expansion(Arg1, Arg2)
 http_reply_file(Arg1, Arg2, Arg3)
 http_redirect(Arg1, Arg2, Arg3)
 http_404(Arg1, Arg2)
 http_switch_protocol(Arg1, Arg2)
 http_current_handler(Arg1, Arg2)
 http_current_handler(Arg1, Arg2, Arg3)
 http_location_by_id(Arg1, Arg2)
 http_link_to_id(Arg1, Arg2, Arg3)
 http_reload_with_parameters(Arg1, Arg2, Arg3)
 http_current_request(Arg1)
 http_peer(Arg1, Arg2)
 html(Arg1, Arg2, Arg3)