Created
February 26, 2025 13:48
-
-
Save jjn1056/a63b21c0a4eaa91f7f41d6817afd0549 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Future::AsyncAwait; | |
# Define an ASGI-like application as an anonymous async sub. | |
# This app checks the request scope and sends a response. | |
my $asgi_app = async sub ($scope, $receive, $send) { | |
if ($scope->{type} eq 'http') { | |
# Send the response start message. | |
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 from a Perl ASGI port using PSGI style!\n", | |
}); | |
} | |
}; | |
# Middleware Example: Logging Middleware | |
# Define a logging middleware that wraps an ASGI app. | |
sub logging_middleware($app) { | |
return async sub ($scope, $receive, $send) { | |
if ($scope->{type} eq 'http') { | |
say "[Middleware] Request received for ", $scope->{path}; | |
} | |
# Call the wrapped application. | |
await $app->($scope, $receive, $send); | |
if ($scope->{type} eq 'http') { | |
say "[Middleware] Request completed"; | |
} | |
} | |
} | |
# Wrap the ASGI app with our logging middleware. | |
my $wrapped_app = logging_middleware($asgi_app); | |
return $wrapped_app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment