httpcookies.lpr 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (* _ _
  2. * | |__ _ __ ___ ___ | | __
  3. * | '_ \| '__/ _ \ / _ \| |/ /
  4. * | |_) | | | (_) | (_) | <
  5. * |_.__/|_| \___/ \___/|_|\_\
  6. *
  7. * Microframework which helps to develop web Pascal applications.
  8. *
  9. * Copyright (c) 2012-2021 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. {$MODE DELPHI}
  27. uses
  28. SysUtils,
  29. BrookHTTPRequest,
  30. BrookHTTPResponse,
  31. BrookHTTPServer;
  32. const
  33. CONTENT_TYPE = 'text/html; charset=utf-8';
  34. INITIAL_PAGE = '<html><head><title>Cookies</title></head><body>Use F5 to refresh this page ...</body></html>';
  35. COUNT_PAGE = '<html><head><title>Cookies</title></head><body>Refresh number: %d</body></html>';
  36. COOKIE_NAME = 'refresh_count';
  37. type
  38. THTTPServer = class(TBrookHTTPServer)
  39. protected
  40. procedure DoRequest(ASender: TObject; ARequest: TBrookHTTPRequest;
  41. AResponse: TBrookHTTPResponse); override;
  42. end;
  43. procedure THTTPServer.DoRequest(ASender: TObject; ARequest: TBrookHTTPRequest;
  44. AResponse: TBrookHTTPResponse);
  45. var
  46. VCount: Integer;
  47. begin
  48. if ARequest.Cookies.IsEmpty then
  49. VCount := 0
  50. else
  51. VCount := StrToIntDef(ARequest.Cookies.Get(COOKIE_NAME), 0);
  52. if VCount = 0 then
  53. begin
  54. AResponse.Send(INITIAL_PAGE, CONTENT_TYPE, 200);
  55. VCount := 1;
  56. end
  57. else
  58. begin
  59. AResponse.SendFmt(COUNT_PAGE, [VCount], CONTENT_TYPE, 200);
  60. Inc(VCount);
  61. end;
  62. AResponse.SetCookie(COOKIE_NAME, VCount.ToString);
  63. end;
  64. begin
  65. with THTTPServer.Create(nil) do
  66. try
  67. NoFavicon := True;
  68. Open;
  69. if not Active then
  70. Exit;
  71. WriteLn('Server running at http://localhost:', Port);
  72. ReadLn;
  73. finally
  74. Free;
  75. end;
  76. end.