How to build a dynamic web application using PSGI

In order to build a web application that can accept input from users we need
to understand how Plack/PSGI defined that
part of the interaction.

Back in the CGI world we had a mix of environment variables in action.
In PSGI everything interesting will be passed via a single parameter
to the anonymous subroutine that implements our application. That parameter
is a reference to a HASH. Let's see what does it contain:

In the script we used the Dumper function of the
standard Data::Dumper module. By default it would print out
the data without any order. Setting the $Data::Dumper::Sortkeys
variable to 1 changes that behavior and the hash keys are sorted. That makes
it a lot easier to read.

We also set the Content-Type to be text/plain.
HTML normally disregards spaces so with this we are telling the visiting browser
to interpret our data as plain text. That way it will display the data verbatim.
Keeping the spaces and the newlines.

The data itself can be divided into two parts. The first part - a set of upper case keys -
are the familiar set of environment variables. The second part is a set of PSGI specific
keys. I won't go over any of these, they are described in the
PSGI specification.

A GET request with parameters

If you are familiar with HTTP then you might want to know how does
a GET request with some parameters show up in this raw data.

Simple echo server

In order to go a small step further, we are going to build a simple
echo server. This is a page with a single entry field and a button.
When you press the button it will reload itself and display the
text you typed in the field.

When processing the input we could parse the QUERY_STRING or the REQUEST_URI
but Plack provides us a nicer way to do this. Plack provides a module called
Plack::Request that provides
a method called param which will return the value of a parameter sent by the user.

In order to simplify the code I created a function called get_html
that returns a piece of static HTML. The form that will be displayed.
The main code checks if the user has passed any parameter. If yes, the
value is attached to the HTML we already have. This is what we have in
the $html variable that we send back to the browser.

Obviously for anything bigger we would move the HTML to a template file
and we would probably even use a higher level Web framework such as
Dancer or Mojolicious,
but we are interested in the low level mechanism now.

A calculator?

If you'd like to take this approach a little bit further
you could take the above script and enhance it to get two
numbers and add them together.

An even more complex example would allow the user to provide two numbers
and one of the basic operators (+, -, *, /) and return the result.