2
0

responseheaders.pp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. (* Feel free to use this example code in any way
  2. you see fit (Public Domain) *)
  3. // Original example: https://gnunet.org/svn/libmicrohttpd/doc/examples/responseheaders.c
  4. program responseheaders;
  5. {$mode objfpc}{$H+}
  6. uses
  7. BaseUnix, SysUtils, libmicrohttpd;
  8. const
  9. PORT = 8888;
  10. FILENAME = 'picture.png';
  11. MIMETYPE = 'image/png';
  12. function AnswerToConnection(ACls: Pointer; AConnection: PMHD_Connection;
  13. AUrl: Pcchar; AMethod: Pcchar; AVersion: Pcchar; AUploadData: Pcchar;
  14. AUploadDataSize: Psize_t; AConCls: PPointer): cint; cdecl;
  15. const
  16. errorstr: Pcchar = '<html><body>An internal server error has occurred!</body></html>';
  17. var
  18. VFd: cint;
  19. VReturn: cint;
  20. VResponse: PMHD_Response;
  21. VSbuf: TStat;
  22. begin
  23. if StrComp(AMethod, 'GET') <> 0 then
  24. Exit(MHD_NO);
  25. VFd := FpOpen(FILENAME, O_RDONLY);
  26. VSbuf := Default(TStat);
  27. if (VFd = -1) or (FpFStat(VFd, VSbuf) <> 0) then
  28. begin
  29. (* error accessing file *)
  30. if VFd <> -1 then
  31. FpClose(VFd);
  32. VResponse := MHD_create_response_from_buffer(Length(errorstr),
  33. Pointer(errorstr), MHD_RESPMEM_PERSISTENT);
  34. if Assigned(VResponse) then
  35. begin
  36. VReturn := MHD_queue_response(AConnection,
  37. MHD_HTTP_INTERNAL_SERVER_ERROR, VResponse);
  38. MHD_destroy_response(VResponse);
  39. Exit(VReturn);
  40. end
  41. else
  42. Exit(MHD_NO);
  43. end;
  44. VResponse := MHD_create_response_from_fd_at_offset64(VSbuf.st_size, VFd, 0);
  45. MHD_add_response_header(VResponse, 'Content-Type', MIMETYPE);
  46. VReturn := MHD_queue_response(AConnection, MHD_HTTP_OK, VResponse);
  47. MHD_destroy_response(VResponse);
  48. Result := VReturn;
  49. end;
  50. var
  51. VDaemon: PMHD_Daemon;
  52. begin
  53. VDaemon := MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, PORT, nil,
  54. nil, @AnswerToConnection, nil, MHD_OPTION_END);
  55. if not Assigned(VDaemon) then
  56. Halt(1);
  57. ReadLn;
  58. MHD_stop_daemon(VDaemon);
  59. end.