program apisamos;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
SysUtils,
Classes,
fphttpapp,
httpdefs,
httproute,
fpjson,
jsonparser;
procedure jsonResponse(var res: TResponse; data: String);
begin
res.Content := data;
res.Code := 200;
res.ContentType := 'application/json';
res.ContentLength := length(res.Content);
res.SendContent;
end;
procedure timeEndpoint(req: TRequest; res: TResponse);
var
jObject : TJSONObject;
begin
jObject := TJSONObject.Create;
try
jObject.Strings['time'] := 'Servidor OK ' + TimeToStr(Time) + req.URI;
jsonResponse(res, jObject.AsJSON);
finally
jObject.Free;
end;
end;
procedure apiEndpoint(req: TRequest; res: TResponse);
var
JSONObject : TJSONObject;
Rota : String;
Metodo : String;
Uri : String;
begin
req.RouteParams[''];
Metodo := req.Method;
Rota := req.RouteParams['name'];
Uri := req.URI;
JSONObject := TJSONObject.Create;
JSONObject := TJSONObject(GetJSON('{"teste":"ok"}'));
JSONResponse(res, JSONObject.AsJSON);
end;
begin
Application.Port := 8080;
HTTPRouter.RegisterRoute('/time' , @timeEndpoint, true);
HTTPRouter.RegisterRoute('/api/:name', @apiEndpoint);
Application.Threaded := true;
writeln('Servidor Rodando: http://localhost:' + IntToStr(Application.Port) + '/time');
Application.Initialize;
Application.Run;
end.