File: responseheaders.pp

package info (click to toggle)
fpc 3.2.0%2Bdfsg-12
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, bullseye-backports
  • size: 338,552 kB
  • sloc: pascal: 3,794,737; xml: 191,997; ansic: 9,637; asm: 8,482; java: 5,346; sh: 4,664; yacc: 3,751; makefile: 2,688; lex: 2,538; javascript: 2,375; sql: 929; php: 473; cpp: 145; perl: 134; sed: 132; csh: 34; tcl: 7
file content (66 lines) | stat: -rw-r--r-- 1,935 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(* Feel free to use this example code in any way
   you see fit (Public Domain) *)

// Original example: https://gnunet.org/svn/libmicrohttpd/doc/examples/responseheaders.c

program responseheaders;

{$mode objfpc}{$H+}

uses
  BaseUnix, SysUtils, libmicrohttpd;

const
  PORT = 8888;
  FILENAME = 'picture.png';
  MIMETYPE = 'image/png';

  function AnswerToConnection(ACls: Pointer; AConnection: PMHD_Connection;
    AUrl: Pcchar; AMethod: Pcchar; AVersion: Pcchar; AUploadData: Pcchar;
    AUploadDataSize: Psize_t; AConCls: PPointer): cint; cdecl;
  const
    errorstr: Pcchar = '<html><body>An internal server error has occurred!</body></html>';
  var
    VFd: cint;
    VReturn: cint;
    VResponse: PMHD_Response;
    VSbuf: TStat;
  begin
    if StrComp(AMethod, 'GET') <> 0 then
      Exit(MHD_NO);
    VFd := FpOpen(FILENAME, O_RDONLY);
    VSbuf := Default(TStat);
    if (VFd = -1) or (FpFStat(VFd, VSbuf) <> 0) then
    begin
      (* error accessing file *)
      if VFd <> -1 then
        FpClose(VFd);
      VResponse := MHD_create_response_from_buffer(Length(errorstr),
        Pointer(errorstr), MHD_RESPMEM_PERSISTENT);
      if Assigned(VResponse) then
      begin
        VReturn := MHD_queue_response(AConnection,
          MHD_HTTP_INTERNAL_SERVER_ERROR, VResponse);
        MHD_destroy_response(VResponse);
        Exit(VReturn);
      end
      else
        Exit(MHD_NO);
    end;
    VResponse := MHD_create_response_from_fd_at_offset64(VSbuf.st_size, VFd, 0);
    MHD_add_response_header(VResponse, 'Content-Type', MIMETYPE);
    VReturn := MHD_queue_response(AConnection, MHD_HTTP_OK, VResponse);
    MHD_destroy_response(VResponse);
    Result := VReturn;
  end;

var
  VDaemon: PMHD_Daemon;
begin
  VDaemon := MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, PORT, nil,
    nil, @AnswerToConnection, nil, MHD_OPTION_END);
  if not Assigned(VDaemon) then
    Halt(1);
  ReadLn;
  MHD_stop_daemon(VDaemon);
end.