Sinatra Basics : Hello World

Objective


To write a hello world Sinatra application and experiment to learn about HTTP Get verb.

Versions


Ruby version 2.2.2. Sinatra version 1.4.6.

Steps


Step 1

Run

$gem install sinatra

Step 2

Create hi.rb file with:

require 'sinatra'

get '/' do
  'hi'
end

Step 3

Run the Sinatra application:

$ ruby hi.rb

Step 4

Browse to http://localhost:4567.
You see the output 'hi'.

Discussion


You can see the port number where the server is running.

[2014-12-09 21:29:16] INFO  WEBrick 1.3.1
[2014-12-09 21:29:16] INFO  ruby 2.1.2 (2014-05-08) [x86_64-darwin11.0]
== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from WEBrick
[2014-12-09 21:29:16] INFO  WEBrick::HTTPServer#start: pid=4860 port=4567
::1 - - [09/Dec/2014:21:29:36 -0800] "GET / HTTP/1.1" 200 2 0.0080
localhost - - [09/Dec/2014:21:29:35 PST] "GET / HTTP/1.1" 200 2

The browser made a GET request to the resource / using HTTP protocol version 1.1. It got a response with status code 200 and content-length 2.

Step 5

Here I copied the output from the terminal where I interact with the webrick server using telnet. Here I connect to webrick and make a HTTP GET request.

$ telnet localhost 4567
Trying ::1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.1

Http Response:

HTTP/1.1 200 OK 
Content-Type: text/html;charset=utf-8
Content-Length: 2
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Server: WEBrick/1.3.1 (Ruby/2.1.2/2014-05-08)
Date: Wed, 10 Dec 2014 05:32:56 GMT
Connection: Keep-Alive

Hi

Http Request + Http Response seen in the above example. The response shows the version of http, with the status code 200, content-length is 2 since we send just 'hi' back to the client. Let's ignore the other headers in the response for now.

Step 6

Let's experiment with Rack in the irb.

$ irb
> require 'rack'
 => true 
> rack_app = lambda{|env| [200, {}, ['Hi Rack']]}
 => #<Proc:0x007fa27d0acec8@(irb):3 (lambda)> 
> Rack::Handler::WEBrick.run rack_app, :Port => 3004
[2014-12-09 22:23:10] INFO  WEBrick 1.3.1
[2014-12-09 22:23:10] INFO  ruby 2.1.2 (2014-05-08) [x86_64-darwin11.0]
[2014-12-09 22:23:10] INFO  WEBrick::HTTPServer#start: pid=5269 port=3004

Browse to http://localhost:3004/

You will see 'Hi Rack'.

The output in the log:

localhost - - [09/Dec/2014:22:24:14 PST] "GET / HTTP/1.1" 200 7

shows the GET request made by the browser for the resource / with HTTP version 1.1. The response shows the status code 200 with the length of the string 'Hi Rack' 7. In this example we did not set any headers in the response (the hash {} is empty in the second parameter.)

Step 7

CTRL+c to stop the server.

Summary


In this article, we wrote a simple hello world program in Sinatra. We played with telnet and rack to learn about GET http verb and request/response.


Related Articles