Routing
In the context of web development, routing describes the process by which a web application receives a request from a browser and decides which code to run order to generate an appropriate response. This process lies at the heart of every web application.
How this works depends on the particular programming languages and libraries used, but the core idea is the same:
- The browser sends a request to our web application.
- Our application looks at the request data.
- Our application routes the request to the appropriate chunk of code.
- Our application calls that chunk of code to generate a response.
- Our application sends the response back to the browser.
- The browser renders the response.
Any routing system will need to express a few key ideas:
- How do we match against the parts of an incoming request?
- How do we specify which code to call for a match?
- How does the code-to-be-called specify the response?
In Sinatra
Keeping the above key ideas in mind, here's a specific example using Sinatra (a web framework for Ruby):
require "sinatra" # Load the Sinatra web framework
# Set up a chunk of code to call when GET requests come to /hello
get("/hello") do
# Generate an HTML response to send to the browser
body("<p>Hello, world!</p>")
end
# Set up a chunk of code to call when POST requests come to /hello
post("/hello") do
# Generate an HTML response to send to the browser
body("<p>Oh, a POST request!</p>")
end
In the above application we're specifying two possible "routing matches" and
the code to be run when a match occurs. The code-to-be-run is defined by the
do ... end
blocks. Remember, this is specific to Sinatra. Other
frameworks will implement routing differently.
Let's answer the general questions from above using this example.
How do we match against the various parts of an incoming request?
We're matching against two parts of the request data:
Given a URL like http://example.com/fancy/pants, the path is everything in the URL after the name of the server (
/fancy/pants
in this case).get("/hello")
matches anyGET
request for a URL with the path/hello
.post("/hello")
matches anyPOST
request for a URL with the path/hello
.How do we specify which code to call for a match?
We specify the code-to-be-called with a
do ... end
block. In the routeget("/hello") do body("<p>Hello, world!</p>") end
the code-to-be-called is everything after the
do
keyword and before the correspondingend
keyword.How does the code-to-be-called specify a response?
We specify a response by calling the
body
method and passing it aString
containing the HTML we want the browser to render. Sinatra will generate the other parts of the request for us and send everything back to the requesting browser.