program apiteste;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
SysUtils,
Classes,
fphttpapp,
httpdefs,
httproute,
fpjson,
jsonparser;
function DecodeUrl(url: string): string;
var
x : integer;
ch : string;
sVal: string;
Buff: string;
begin
//Init
Buff := '';
x := 1;
while x <= Length(url) do
begin
ch := url[x];
if ch = '+' then
Buff := Buff + ' '
else
if ch <> '%' then
Buff := Buff + ch
else
begin
sVal := Copy(url, x + 1, 2);
Buff := Buff + char(StrToInt('$' + sVal));
Inc(x, 2);
end;
Inc(x);
end;
Result := Buff;
end;
procedure JSONResponse(var res: TResponse; data: String);
begin
res.Content := data;
res.Code := 200;
res.SetFieldByName('Access-Control-Allow-Origin', '*');
res.SetFieldByName('Access-Control-Allow-Methods','GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.SetFieldByName('Access-Control-Allow-Headers','*');
res.ContentType := 'application/json';
res.ContentLength := length(res.Content);
res.SendContent;
end;
procedure TimeEndPoint(req: TRequest; res: TResponse);
var
JSONObject : TJSONObject;
begin
JSONObject := TJSONObject.Create;
try
JSONObject.Strings['time'] := 'Servidor OK ' + TimeToStr(Time) + req.URI;
jsonResponse(res, JSONObject.AsJSON);
finally
JSONObject.Free;
end;
end;
procedure ApiEndpoint(req: TRequest; res: TResponse);
var
JSONObject : TJSONObject;
Rota : String;
Metodo : String;
Uri : String;
begin
req.RouteParams[''];
Metodo := req.Method; // Aqui estou recebendo OPTIONS quando chamo pelo navegador
Rota := req.RouteParams['name'];
Uri := DecodeURL(req.URI);
JSONObject := TJSONObject.Create;
try
if Metodo = 'GET' then
JSONObject.Strings['get'] := 'OK -> ' + Rota
else
if Metodo = 'POST' then
JSONObject.Strings['post'] := 'OK -> ' + Rota
else
if Metodo = 'PUT' then
JSONObject.Strings['put'] := 'OK -> ' + Rota
else
if Metodo = 'DELETE' then
JSONObject.Strings['delete'] := 'OK -> ' + Rota;
JSONResponse(res, JSONObject.AsJSON);
finally
FreeAndNil(JSONObject);
end;
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.