lazarus开发应用提供http接口

发布于:2023-09-15 ⋅ 阅读:(79) ⋅ 点赞:(0)

lazarus开发应用提供http接口,简单试用了一下fphttpapp,发现非常易用,直接支持中文内容

引用3个核心单元

fphttpapp, httpdefs, httproute

启用端口定义路由

procedure route1(aReq: TRequest; aResp: TResponse);
begin
  aResp.Content:='<html><head><title>欢迎测试</title></head><body><h1>Route 1 The Default</h1>欢迎测试</body></html>';
end;

procedure route2(aReq: TRequest; aResp: TResponse);
begin
  aResp.Content:='<html><body><h1>lazarus提供http接口</h1></body></html>';
end;

procedure TForm1.StaticText1Click(Sender: TObject);
begin
HTTPRouter.RegisterRoute('', @route1);
   HTTPRouter.RegisterRoute('/', @route1);
  HTTPRouter.RegisterRoute('/2', @route2);
  fphttpapp.Application.Port := 8088;
  fphttpapp.Application.Threaded := true;
  fphttpapp.Application.Initialize;
//fphttpapp.Application.Run;
 // Run the server in a thread.
  TWebServerThread.Create(false); // false means the server thread runs immediately

end;

如果是无界面应用可以直接启动,这里是有界面应用,所以再写一个线程启动监听更加好用

下面是定以线程和线程启动http服务

type
     TWebServerThread = class(TThread)
    protected
      procedure Execute; override;
    public
      constructor Create(CreateSuspended: boolean);
  end;
  { TForm1 }
......
implementation

{$R *.lfm}

constructor TWebServerThread.Create(CreateSuspended: boolean);
begin
  inherited Create(CreateSuspended);
  FreeOnTerminate := true;
end;

procedure TWebServerThread.Execute;
begin
       writeln(' fphttpapp.Application.Run');
  fphttpapp.Application.Run;
end;