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

% 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

	% 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

	% display index.pwp

Save this as, 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.


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

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

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.