-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathHTTP.Server.pas
436 lines (365 loc) · 11.1 KB
/
HTTP.Server.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
unit HTTP.Server;
interface
uses
System.Classes, System.SysUtils, System.Threading, IdContext, System.Rtti,
IdCustomHTTPServer, IdHTTPServer, System.IOUtils, System.Generics.Collections,
System.JSON;
type
TRequest = TIdHTTPRequestInfo;
TRequestHelper = class helper for TRequest
public
function IsHead: Boolean;
function IsGet: Boolean;
function IsPost: Boolean;
function IsDelete: Boolean;
function IsPut: Boolean;
function IsTrace: Boolean;
function IsOption: Boolean;
end;
TResponse = TIdHTTPResponseInfo;
TResponseHelper = class helper for TResponse
public
procedure Json(const Text: string; Code: Integer = 200); overload;
procedure Json(const JSONValue: TJSONValue; Code: Integer = 200); overload;
procedure Json(const Obj: TObject; Code: Integer = 200); overload;
procedure AsFile(const FileName: string; Code: Integer = 200);
end;
TOnRequest = reference to procedure(Request: TRequest; Response: TResponse);
TOnResponsePlainText = reference to procedure(var Response: string; var Code: Word);
TOnRequestProc = procedure(Request: TRequest; Response: TResponse) of object;
THTTPCommand = (HEAD, GET, POST, DELETE, PUT, TRACE, OPTION);
THTTPCommands = set of THTTPCommand;
THTTPCommandTypes = set of THTTPCommandType;
THTTPCommandsHelper = record helper for THTTPCommands
function ToHTTPCommandTypes: THTTPCommandTypes;
end;
TRoute = class
URI: string;
Method: THTTPCommandTypes;
function CheckURI(Request: TRequest): Boolean;
constructor Create; overload;
constructor Create(const URI: string); overload;
constructor Create(Method: THTTPCommandTypes; const URI: string); overload;
procedure Execute(Request: TRequest; Response: TResponse); virtual; abstract;
public
end;
TRouteFull = class(TRoute)
protected
Proc: TOnRequest;
public
constructor Create(const URI: string; Proc: TOnRequest); overload;
constructor Create(Method: THTTPCommandTypes; const URI: string; Proc: TOnRequest); overload;
procedure Execute(Request: TRequest; Response: TResponse); override;
end;
TRoutePlaiText = class(TRoute)
protected
Proc: TOnResponsePlainText;
public
constructor Create(const URI: string; Proc: TOnResponsePlainText); overload;
constructor Create(Method: THTTPCommandTypes; const URI: string; Proc: TOnResponsePlainText); overload;
procedure Execute(Request: TRequest; Response: TResponse); override;
end;
RouteMethod = class(TCustomAttribute)
private
URI: string;
Method: THTTPCommands;
public
constructor Create(const URI: string; Method: THTTPCommands = []);
end;
TRoutes = class(TObjectList<TRoute>)
end;
TOnServerWork = reference to procedure(var Stop: Boolean);
TOnServerErrorBind = reference to procedure;
THTTPServer = class(TComponent)
private
FRoutes: TRoutes;
FContentPath: string;
Instance: TidHTTPServer;
FAutoFileServer: Boolean;
function ProcRequest(Request: TRequest; Response: TResponse): Boolean;
procedure FillRoutes;
procedure SetAutoFileServer(const Value: Boolean);
protected
procedure DoCommand(AContext: TIdContext; Request: TRequest; Response: TResponse);
function GetFilePath(const FileName: string): string;
public
constructor Create; reintroduce; overload;
constructor Create(AOwner: TComponent); overload; override;
destructor Destroy; override;
procedure AddMimeType(const Ext, MIMEType: string);
procedure Run(const Ports: TArray<Word> = []); overload;
procedure RunSync(const Port: Word);
procedure Route(const URI: string; Proc: TOnRequest); overload;
procedure Route(Method: THTTPCommands; const URI: string; Proc: TOnRequest); overload;
procedure Route(Method: THTTPCommands; const URI: string; Proc: TOnResponsePlainText); overload;
procedure Route(const URI: string; Proc: TOnResponsePlainText); overload;
procedure Route(Method: THTTPCommands; const URI: string; Proc: TRttiMethod); overload;
property ContentPath: string read FContentPath write FContentPath;
property AutoFileServer: Boolean read FAutoFileServer write SetAutoFileServer;
end;
implementation
uses
REST.Json;
procedure THTTPServer.AddMimeType(const Ext, MIMEType: string);
begin
Instance.MIMETable.AddMimeType(Ext, MIMEType);
end;
constructor THTTPServer.Create;
begin
Create(nil);
end;
constructor THTTPServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAutoFileServer := False;
FContentPath := 'www';
FRoutes := TRoutes.Create;
Instance := TidHTTPServer.Create(nil);
Instance.OnCommandGet := DoCommand;
Instance.OnCommandOther := DoCommand;
Instance.MIMETable.BuildCache;
Instance.MIMETable.AddMimeType('wasm', 'application/wasm');
FillRoutes;
end;
destructor THTTPServer.Destroy;
begin
FRoutes.Free;
Instance.Free;
inherited;
end;
procedure THTTPServer.FillRoutes;
var
Context: TRttiContext;
begin
for var Method in Context.GetType(ClassInfo).GetMethods do
for var Attr in Method.GetAttributes do
if Attr is RouteMethod then
Route(RouteMethod(Attr).Method, RouteMethod(Attr).URI, Method);
end;
procedure THTTPServer.DoCommand(AContext: TIdContext; Request: TRequest; Response: TResponse);
begin
//Writeln(Request.RemoteIP, ' ', Request.Command, ' ', Request.URI, ' ', Request.QueryParams, ' ', Request.Range);
if FAutoFileServer and (Request.CommandType in [hcGET, hcHEAD]) then
begin
var Path := Request.URI;
if TFile.Exists(GetFilePath(Path)) then
begin
Response.AsFile(GetFilePath(Path));
Exit;
end;
end;
if not ProcRequest(Request, Response) then
Response.ResponseNo := 404;
end;
function THTTPServer.GetFilePath(const FileName: string): string;
begin
Result := TPath.Combine(FContentPath, FileName.TrimLeft(['/']));
end;
function THTTPServer.ProcRequest(Request: TRequest; Response: TResponse): Boolean;
begin
for var Route in FRoutes do
if Route.CheckURI(Request) then
begin
Route.Execute(Request, Response);
Exit(True);
end;
Result := False;
end;
procedure THTTPServer.Route(Method: THTTPCommands; const URI: string; Proc: TRttiMethod);
begin
var LMethod: TMethod;
LMethod.Code := Proc.CodeAddress;
LMethod.Data := Self;
FRoutes.Add(TRouteFull.Create(Method.ToHTTPCommandTypes, URI, TOnRequestProc(LMethod)));
end;
procedure THTTPServer.Route(const URI: string; Proc: TOnResponsePlainText);
begin
FRoutes.Add(TRoutePlaiText.Create([], URI, Proc));
end;
procedure THTTPServer.Route(Method: THTTPCommands; const URI: string; Proc: TOnResponsePlainText);
begin
FRoutes.Add(TRoutePlaiText.Create(Method.ToHTTPCommandTypes, URI, Proc));
end;
procedure THTTPServer.Route(Method: THTTPCommands; const URI: string; Proc: TOnRequest);
begin
FRoutes.Add(TRouteFull.Create(Method.ToHTTPCommandTypes, URI, Proc));
end;
procedure THTTPServer.Route(const URI: string; Proc: TOnRequest);
begin
Route([], URI, Proc);
end;
procedure THTTPServer.RunSync(const Port: Word);
begin
Instance.Bindings.Add.Port := Port;
Instance.Active := True;
end;
procedure THTTPServer.Run(const Ports: TArray<Word>);
begin
var command: string;
Writeln('Starting...');
repeat
try
TTask.Run(
procedure
begin
for var Port in Ports do
if Port <> 0 then
Instance.Bindings.Add.Port := Port;
Instance.Active := True;
end);
Writeln('Started');
repeat
Readln(command)
until command = 'quit';
except
on E: Exception do
begin
Writeln(E.ClassName + ': ' + E.Message);
Sleep(1000);
Writeln('Restaring...');
end;
end;
until command = 'quit';
end;
procedure THTTPServer.SetAutoFileServer(const Value: Boolean);
begin
FAutoFileServer := Value;
end;
{ RouteMethod }
constructor RouteMethod.Create(const URI: string; Method: THTTPCommands);
begin
inherited Create;
Self.URI := URI;
Self.Method := Method;
end;
{ TResponseHelper }
procedure TResponseHelper.Json(const Text: string; Code: Integer);
begin
ContentText := Text;
ContentType := 'application/json';
ResponseNo := Code;
end;
procedure TResponseHelper.Json(const JSONValue: TJSONValue; Code: Integer);
begin
try
Json(JSONValue.ToJSON, Code);
finally
JSONValue.Free;
end;
end;
procedure TResponseHelper.AsFile(const FileName: string; Code: Integer);
begin
ContentType := HTTPServer.MIMETable.GetFileMIMEType(FileName);
//ContentLength := TFile.GetSize(FileName);
ContentStream := TFileStream.Create(FileName, fmShareDenyWrite);
ResponseNo := Code;
end;
procedure TResponseHelper.Json(const Obj: TObject; Code: Integer);
begin
Json(TJson.ObjectToJsonString(Obj), Code);
end;
{ TRequestHelper }
function TRequestHelper.IsDelete: Boolean;
begin
Result := CommandType = hcDELETE;
end;
function TRequestHelper.IsGet: Boolean;
begin
Result := CommandType = hcGET;
end;
function TRequestHelper.IsHead: Boolean;
begin
Result := CommandType = hcHEAD;
end;
function TRequestHelper.IsOption: Boolean;
begin
Result := CommandType = hcOPTION;
end;
function TRequestHelper.IsPost: Boolean;
begin
Result := CommandType = hcPOST;
end;
function TRequestHelper.IsPut: Boolean;
begin
Result := CommandType = hcPUT;
end;
function TRequestHelper.IsTrace: Boolean;
begin
Result := CommandType = hcTRACE;
end;
{ THTTPCommandsHelper }
function THTTPCommandsHelper.ToHTTPCommandTypes: THTTPCommandTypes;
begin
if GET in Self then
Include(Result, hcGET);
if HEAD in Self then
Include(Result, hcHEAD);
if POST in Self then
Include(Result, hcPOST);
if DELETE in Self then
Include(Result, hcDELETE);
if PUT in Self then
Include(Result, hcPUT);
if TRACE in Self then
Include(Result, hcTRACE);
if OPTION in Self then
Include(Result, hcOPTION);
end;
{ TRoute }
function TRoute.CheckURI(Request: TRequest): Boolean;
begin
Result := ((Method = []) or (Request.CommandType in Method)) and (Request.URI = URI);
end;
constructor TRoute.Create(const URI: string);
begin
Create([], URI);
end;
constructor TRoute.Create(Method: THTTPCommandTypes; const URI: string);
begin
inherited Create;
Self.Method := Method;
Self.URI := URI;
end;
constructor TRoute.Create;
begin
inherited;
Method := [];
URI := '';
end;
{ TRouteFull }
constructor TRouteFull.Create(const URI: string; Proc: TOnRequest);
begin
inherited Create(URI);
Self.Proc := Proc;
end;
constructor TRouteFull.Create(Method: THTTPCommandTypes; const URI: string; Proc: TOnRequest);
begin
inherited Create(Method, URI);
Self.Proc := Proc;
end;
procedure TRouteFull.Execute(Request: TRequest; Response: TResponse);
begin
Proc(Request, Response);
end;
{ TRoutePlaiText }
constructor TRoutePlaiText.Create(const URI: string; Proc: TOnResponsePlainText);
begin
inherited Create(URI);
Self.Proc := Proc;
end;
constructor TRoutePlaiText.Create(Method: THTTPCommandTypes; const URI: string; Proc: TOnResponsePlainText);
begin
inherited Create(Method, URI);
Self.Proc := Proc;
end;
procedure TRoutePlaiText.Execute(Request: TRequest; Response: TResponse);
var
ResponseText: string;
ResponseCode: Word;
begin
ResponseCode := 200;
Proc(ResponseText, ResponseCode);
Response.ContentText := ResponseText;
Response.ResponseNo := ResponseCode;
end;
end.