simpleserver.pas 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. program simpleserver;
  2. uses sysutils,custhttpapp, fpwebfile;
  3. Type
  4. { THTTPApplication }
  5. THTTPApplication = Class(TCustomHTTPApplication)
  6. private
  7. FQuiet: Boolean;
  8. procedure Usage(Msg: String);
  9. published
  10. procedure DoLog(EventType: TEventType; const Msg: String); override;
  11. Procedure DoRun; override;
  12. property Quiet : Boolean read FQuiet Write FQuiet;
  13. end;
  14. Var
  15. Application : THTTPApplication;
  16. { THTTPApplication }
  17. procedure THTTPApplication.DoLog(EventType: TEventType; const Msg: String);
  18. begin
  19. if Quiet then
  20. exit;
  21. if IsConsole then
  22. Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Now),' [',EventType,'] ',Msg)
  23. else
  24. inherited DoLog(EventType, Msg);
  25. end;
  26. procedure THTTPApplication.Usage(Msg : String);
  27. begin
  28. if (Msg<>'') then
  29. Writeln('Error: ',Msg);
  30. Writeln('Usage ',ExtractFileName(ParamStr(0)),' [options] ');
  31. Writeln('Where options is one or more of : ');
  32. Writeln('-d --directory=dir Base directory from which to serve files.');
  33. Writeln(' Default is current working directory: ',GetCurrentDir);
  34. Writeln('-h --help This help text');
  35. Writeln('-i --indexpage=name Directory index page to use (default: index.html)');
  36. Writeln('-n --noindexpage Do not allow index page.');
  37. Writeln('-p --port=NNNN TCP/IP port to listen on (default is 3000)');
  38. Writeln('-q --quiet Do not write diagnostic messages');
  39. Halt(Ord(Msg<>''));
  40. end;
  41. procedure THTTPApplication.DoRun;
  42. Var
  43. S,IndexPage,D : String;
  44. begin
  45. S:=Checkoptions('hqd:ni:p:',['help','quiet','noindexpage','directory:','port:','indexpage:']);
  46. if (S<>'') or HasOption('h','help') then
  47. usage(S);
  48. Quiet:=HasOption('q','quiet');
  49. Port:=StrToIntDef(GetOptionValue('p','port'),3000);
  50. D:=GetOptionValue('d','directory');
  51. if D='' then
  52. D:=GetCurrentDir;
  53. Log(etInfo,'Listening on port %d, serving files from directory: %s',[Port,D]);
  54. {$ifdef unix}
  55. MimeTypesFile:='/etc/mime.types';
  56. {$endif}
  57. TSimpleFileModule.BaseDir:=IncludeTrailingPathDelimiter(D);
  58. TSimpleFileModule.OnLog:=@Log;
  59. If not HasOption('n','noindexpage') then
  60. begin
  61. IndexPage:=GetOptionValue('i','indexpage');
  62. if IndexPage='' then
  63. IndexPage:='index.html';
  64. Log(etInfo,'Using index page %s',[IndexPage]);
  65. TSimpleFileModule.IndexPageName:=IndexPage;
  66. end;
  67. inherited;
  68. end;
  69. begin
  70. TSimpleFileModule.RegisterDefaultRoute;
  71. Application:=THTTPApplication.Create(Nil);
  72. Application.Initialize;
  73. Application.Run;
  74. Application.Free;
  75. end.