Skip to content

Instantly share code, notes, and snippets.

@jjn1056
Created February 26, 2025 01:34
Show Gist options
  • Save jjn1056/d01593362d6ffde202cf87aefc4527fa to your computer and use it in GitHub Desktop.
Save jjn1056/d01593362d6ffde202cf87aefc4527fa to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strictures;
use PSGI::Syntax; #(signatures, etc. for example code)
use Future::AsyncAwait;
use Future;
### Basic ASGI App Implementation
async sub app($scope, $receive, $send) {
if ($scope->{type} eq 'http') {
# Start the HTTP response.
await $send->({
type => "http.response.start",
status => 200,
headers => [
["content-type", "text/plain"],
],
});
# Send the response body.
await $send->({
type => "http.response.body",
body => "Hello, ASGI with middleware!",
});
}
}
### Logging Middleware Package
{
package LoggingMiddleware;
use strictures;
use PSGI::Syntax; #(signatures, etc. for example code)
use Future::AsyncAwait;
use Future;
# Constructor: wraps an ASGI app.
sub new($class, $app) {
return bless { app => $app }, $class;
}
# The middleware call method which logs before and after calling the app.
async sub call($self, $scope, $receive, $send) {
if ($scope->{type} eq 'http') {
say "[Middleware] Request received: $scope->{path}";
}
# Call the next app (or middleware) in the stack.
await $self->{app}->($scope, $receive, $send);
if ($scope->{type} eq 'http') {
say "[Middleware] Request processing completed.";
}
}
}
### Main Execution
# Wrap the basic app with logging middleware.
my $app_with_middleware = LoggingMiddleware->new(\&app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment