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.
- 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?
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:
How do we specify which code to call for a match?
We specify the code-to-be-called with a
do ... endblock. In the route
get("/hello") do body("<p>Hello, world!</p>") end
the code-to-be-called is everything after the
dokeyword and before the corresponding
How does the code-to-be-called specify a response?
We specify a response by calling the
bodymethod and passing it a
Stringcontaining 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.