httpcookies.dpr 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. (* _ _
  2. * | |__ _ __ ___ ___ | | __
  3. * | '_ \| '__/ _ \ / _ \| |/ /
  4. * | |_) | | | (_) | (_) | <
  5. * |_.__/|_| \___/ \___/|_|\_\
  6. *
  7. * Microframework which helps to develop web Pascal applications.
  8. *
  9. * Copyright (c) 2012-2020 Silvio Clecio <[email protected]>
  10. *
  11. * Brook framework is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * Brook framework is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with Brook framework; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. *)
  25. program httpcookies;
  26. {$IFDEF MSWINDOWS}
  27. {$APPTYPE CONSOLE}
  28. {$ENDIF}
  29. uses
  30. SysUtils,
  31. BrookHTTPRequest,
  32. BrookHTTPResponse,
  33. BrookHTTPServer;
  34. const
  35. CONTENT_TYPE = 'text/html; charset=utf-8';
  36. INITIAL_PAGE = '<html><head><title>Cookies</title></head><body>Use F5 to refresh this page ...</body></html>';
  37. COUNT_PAGE = '<html><head><title>Cookies</title></head><body>Refresh number: %d</body></html>';
  38. COOKIE_NAME = 'refresh_count';
  39. type
  40. THTTPServer = class(TBrookHTTPServer)
  41. protected
  42. procedure DoRequest(ASender: TObject; ARequest: TBrookHTTPRequest;
  43. AResponse: TBrookHTTPResponse); override;
  44. end;
  45. procedure THTTPServer.DoRequest(ASender: TObject; ARequest: TBrookHTTPRequest;
  46. AResponse: TBrookHTTPResponse);
  47. var
  48. VCount: Integer;
  49. begin
  50. if ARequest.Cookies.IsEmpty then
  51. VCount := 0
  52. else
  53. VCount := StrToIntDef(ARequest.Cookies.Get(COOKIE_NAME), 0);
  54. if VCount = 0 then
  55. begin
  56. AResponse.Send(INITIAL_PAGE, CONTENT_TYPE, 200);
  57. VCount := 1;
  58. end
  59. else
  60. begin
  61. AResponse.SendFmt(COUNT_PAGE, [VCount], CONTENT_TYPE, 200);
  62. Inc(VCount);
  63. end;
  64. AResponse.SetCookie(COOKIE_NAME, VCount.ToString);
  65. end;
  66. begin
  67. with THTTPServer.Create(nil) do
  68. try
  69. NoFavicon := True;
  70. Open;
  71. if not Active then
  72. Exit;
  73. WriteLn('Server running at http://localhost:', Port);
  74. ReadLn;
  75. finally
  76. Free;
  77. end;
  78. end.