HttpRouterAdvancedHandlers topic
Advanced HTTP Router Handler Examples
Declaration
HttpRouterAdvancedHandlersDescription
Beyond simple procedure callbacks, the HTTP router supports sophisticated handler patterns for complex applications. These examples demonstrate method events, interface handlers, and object class handlers.
// Method Event Handler Example
type
TAPIHandler = class
private
FVersion: String;
public
constructor Create(const AVersion: String);
procedure HandleVersionInfo(ARequest: TRequest; AResponse: TResponse);
end;
constructor TAPIHandler.Create(const AVersion: String);
begin
inherited Create;
FVersion := AVersion;
end;
procedure TAPIHandler.HandleVersionInfo(ARequest: TRequest; AResponse: TResponse);
begin
AResponse.Content := Format('{"version": "%s"}', [FVersion]);
AResponse.ContentType := 'application/json';
end;
// Interface Handler Example
type
IUserService = interface(IRouteInterface)
['{12345678-1234-1234-1234-123456789012}']
end;
TUserService = class(TInterfacedObject, IUserService)
public
procedure HandleRequest(ARequest: TRequest; AResponse: TResponse);
end;
procedure TUserService.HandleRequest(ARequest: TRequest; AResponse: TResponse);
begin
AResponse.Content := 'User service response';
end;
// Object Class Handler Example
type
TRequestProcessor = class(TRouteObject)
public
procedure HandleRequest(ARequest: TRequest; AResponse: TResponse); override;
end;
procedure TRequestProcessor.HandleRequest(ARequest: TRequest; AResponse: TResponse);
begin
AResponse.Content := 'Processed by object instance';
end;
// Registration examples:
var
APIHandler: TAPIHandler;
UserService: IUserService;
begin
APIHandler := TAPIHandler.Create('1.0');
UserService := TUserService.Create;
// Register method event
HTTPRouter.RegisterRoute('/version', rmGet, @APIHandler.HandleVersionInfo);
// Register interface handler
HTTPRouter.RegisterRoute('/users', rmGet, UserService);
// Register object class handler
HTTPRouter.RegisterRoute('/process', rmPost, TRequestProcessor);
end.
These examples simply demonstrate the core functionality of the HTTP router.
An actual implementation would typically integrate with an HTTP server framework
like fpweb or fphttp to handle incoming requests, and
would use one of the various request-handling units such as httpapp or cgiapp.
An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.
