Creating Webpages with SWI-Prolog and PWP: Starting a Server

This is Part 3 in a series of tutorials about Creating Webpages with SWI-Prolog and PWP.

Before displaying Prolog-driven pages in a browser, you must create a server to handle the HTTP requests. In its most basic form, the server must handle HTTP requests.

A basic server setup in SWI-Prolog looks like:

% include some libraries
:-use_module(library(http/thread_httpd)).
:-use_module(library(http/http_dispatch)).
:-use_module(library(http/http_pwp)).

% setup a handler to tell prolog what to do when the user visits the root of the website
:- http_handler(/, default_handler, []).

% predicate to start the server
server(Port):-

	% start server on specified port
	http_server(http_dispatch, [port(Port)]).

% Used by http_handler to determine what to do when handling the HTTP request
default_handler(Request):-

	% display index.pwp
	reply_pwp_page('index.pwp',[],Request).

Save this as server.pl, load it into the interactive console and start the server and provide a Port number.

?- consult(server).
?- server(8000).

Finally, navigate to http://localhost:8000 (replace 8000 with your desired port) to see what happens.

swipl_server01

For now, you should get an error, “source_sink `’index.pwp” does not exist”. This is because we haven’t created index.pwp yet. Go ahead and create a new file similar to the one below, add some simple HTML and save it as index.pwp, in the same directory as server.pl.

<html>
	<head>
		<title>Hello World</title>
	</head>
	<body>
		Powered by SWI-Prolog!
	</body>
</html>

With your Prolog HTTP server still running, visit http://localhost:8000 again. You should see index.pwp rendered in the browser.

Visit the next tutorial in this series on Creating Webpages with SWI-Prolog and PWP: Handling Assets.