Serve static webpages with FreePascal

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Serve static webpages with FreePascal
Marcus Fernström

[SHOWTOGROUPS=4,20]Serve static webpages with FreePascal
Marcus Fernström

In the past I’ve talked about Для просмотра ссылки Войди или Зарегистрируйся, Для просмотра ссылки Войди или Зарегистрируйся, Для просмотра ссылки Войди или Зарегистрируйся, and whatnot.

But sometimes all you need is to just serve html files and their related CSS, JS, and images.

A common pattern is to create the web front-end as static web pages where all application functionality is driven through AJAX or web sockets.

Using FreePascal to serve those static pages is very simple.

Here’s the complete program, you can use it as a starting point for your own web server, it’s also available on Для просмотра ссылки Войди или Зарегистрируйся with the excellent Skeleton boilerplate and a mime-types file included.

Код:
{
  Web server template for serving static files
  Copyright 2020 - Marcus Fernstrom
  License - Apache 2.0
  GitHub - https://github.com/MFernstrom/static-file-webserver
  Mimefile is licensed Apache 2.0 and was sourced from http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=markup
}
program StaticServer;
uses
  SysUtils,
  fphttpapp,
  httproute,
  HTTPDefs,
  fpwebfile;
const
  port = 8080;
  fileLocation = 'app';
procedure rerouteRoot(aRequest: TRequest; aResponse: TResponse);
  begin
    aResponse.Code := 301;
    aResponse.SetCustomHeader('Location', fileLocation + '/index.html');
    aResponse.SendContent;
  end;
begin
  Application.Initialize;
  RegisterFileLocation(fileLocation, 'public_html');
  HTTPRouter.RegisterRoute('/', @rerouteRoot);
  MimeTypesFile := extractfiledir(ParamStr(0)) + PathDelim + 'mime.types';
  Application.Port := port;
  WriteLn(format('Static HTTP server starting on localhost:%d', [port]));
  Application.Run;
end.

As you can see, you don’t really need much to serve static files.

Two constants, port which is where we define what port the server runs on, and fileLocation which is the uri path to where the files will be served.

The program requires the mime.types file to be present in the same folder as the program, and for there to be a directory called public_html in there as well.

Let’s say you add a file, index.html, to your public_html directory. When you run the server, it’ll be available at Для просмотра ссылки Войди или Зарегистрируйся

If you download the GitHub project you’ll see that I’ve included the Skeleton framework as an example.

We have a single procedure called rerouteRoot whose only purpose is to redirect requests for the root path, to the index file under the fileLocation path.

If you run the server and type in Для просмотра ссылки Войди или Зарегистрируйся the rerouteRoot procedure will respond with a redirect header that takes you to Для просмотра ссылки Войди или Зарегистрируйся instead.

The mime.types file is an extensive list of what mime-type to use for what extension. Mime types lets the browser know what kind of file your server is responding with so it’s displayed or otherwise used properly.

Let’s take a quick look at a few lines from the programs core begin/end block

Код:
begin
  Application.Initialize;
  RegisterFileLocation(fileLocation, 'public_html');
  HTTPRouter.RegisterRoute('/', @rerouteRoot);
  MimeTypesFile := extractfiledir(ParamStr(0)) + PathDelim + 'mime.types';
  Application.Port := port;
  WriteLn(format('Static HTTP server starting on localhost:%d', [port]));
  Application.Run;
end.

The RegisterFileLocation procedure is where we tell the webserver at what path we want to serve the file and from what folder. It takes two string arguments, the uri location and the directory location.

Then we use HTTPRouter.RegisterRoute to make sure all requests to the root path / goes to the rerouteRoot procedure instead of ending up with an error message.

Next up we tell the web-server where to find the mime-types file by setting MimeTypesFile

It takes a full path so we extract the path to the program with ExtractFilePath which takes a filename, and returns the directory path including a trailing delimiter. To that we just append the filename of the mime-types file.

Setting the port should be self-explanatory and finally we start the server with Application.run

You’ve learned two very useful things in this short article.

  1. How to serve static files
  2. That you can mix static files with routes to perform actions
Now go make some cool stuff![/SHOWTOGROUPS]