At this stage, you should have the following script, which is a barebone, simple-yet-complete web application.
class App
def call(env)
# a hash containing response headers
headers = {
"Content-Type" => "text/html"
}
# an array containing the HTML response string
response = ["<h1>Hello World</h1>"]
# an array containing
# 1. HTTP status code
# 2. HTTP headers
# 3. HTTP response
[200, headers, response]
end
end
Right now, our application does only one thing. Whenever a request arrives, it returns the response Hello World
to the browser. It sends the same response, regardless of the request URL.
➜ curl localhost:9292
<h1>Hello World</h1>
➜ curl localhost:9292/posts
<h1>Hello World</h1>
➜ curl localhost:9292/posts/new
<h1>Hello World</h1>
Having a web application that returns the same response for every request isn't very exciting... or useful! Let's make it smart by returning a different response based on the incoming HTTP request's path.
To keep things simple, I'll make the following assumptions:
Our application only supports HTTP GET requests,
It only needs to handle a specific set of routes shown below.
For all other URLs, it returns
no route found
message.
Here're the URL patterns and corresponding actions our application will perform:
/
: shows the home page/articles
: shows all articles/articles/1
: shows a single article/random
: "no route found"
Let's get to it.