tiny_monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Perl monks. I was able to write and run a PSGI middleware that validates a form. However, the problem is that I am not sure whether I did it correctly. What I did is that I mapped the middleware, $form_validator, instead of the wrapped PSGI application, $greeting. My code below will display a simple HTML form with a field name 'Taste of Vinegar' and a submit button. When you type in 'sour' and submit the form, the middleware, $form_validator, will be invoked to perform the validation. If all is well, then the PSGI application, $greeting, will be invoked. I am new to Perl/PSGI and I am not sure if I'm doing this correctly. I'd appreciate all of your comments on this. Best regards. :)

#!/usr/bin/perl use strict; use warnings; use Plack::Request; use Plack::Response; my $greeting = sub { return [ '200', [ 'Content-Type' => 'text/html' ], [ "<html> <body> <p>Congratulations! Your answe +r is correct!</p> </body> </html>"], ]; }; my $form_validator = sub { my $env = shift; # PSGI en +v my $request = Plack::Request->new($env); # new Pla +ck::Request my $taste = $request->param('taste'); if ($taste eq 'sour') { return $greeting->($env); } else { my $response = $request->new_response(200);; # + new Plack::Response $response->headers({ 'Content-Type' => 'text/html' }) +; $response->content('<html><body><p>Wrong answer!</p></ +body></html>' ); return $response->finalize; } }; my $form = sub { return [ 200, ['Content-Type' => 'text/html'], ["<html> <body> <form action='submit' method='GET'> Taste of Vinegar <input type='text' name=' +taste'/> <input type='submit' value='SUBMIT' /> </form> </body> </html>"] ]; }; my %routing = ( '/submit' => $form_validator, '/' => $form, ); my $app = sub { my $env = shift; # PSGI env my $request = Plack::Request->new($env); my $route = $routing{$request->path_info}; if ($route) {return $route->($env);} else { return [ '404', [ 'Content-Type' => 'text/html' ], [ '404 Not Found' ], ]; } };

Replies are listed 'Best First'.
Re: Is it required to map a Plack/PSGI middleware?
by Anonymous Monk on Sep 12, 2015 at 03:17 UTC

      That's a good question. It's because at this point I'm still learning how to write my own middleware. I don't think the Perl Advent Calendar requires the use of those modules if one is merely writing one's own middleware. :) I'd appreciate your further comment. Thank you.

Re: Is it required to map a Plack/PSGI middleware?
by Anonymous Monk on Sep 12, 2015 at 03:14 UTC

      Mapping in this case simply means the routing or the redirection of a request. I included a dispatch table in the code:

      my %routing = ( '/submit' => $form_validator, '/' => $form, );

      When you submit the HTML form, it is sent to the URL '/submit' as defined by the HTML form attribute 'action'. Since '/submit' is associated with $form_validator, the anonymous function that the $form_validator refers to is invoked.