Class: Amber::Http::Response

Inherits:
Amber::Http show all
Defined in:
lib/amber/http/response.rb

Constant Summary collapse

TEXT_CONTENT =
"text/plain"
HTML_CONTENT =
"text/html"
JSON_CONTENT =
"application/json"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Response

Returns a new instance of Response.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/amber/http/response.rb', line 8

def initialize(socket)
  super

  @status_table = {
    "100" => "Continue",
    "200" => "OK",
    "300" => "Multiple Choices",
    "301" => "Moved Permanently",
    "400" => "Bad Request",
    "401" => "Unauthorized",
    "403" => "Forbidden",
    "404" => "Not Found",
    "500" => "Internal Server Error",
    "502" => "Bad Gateway",
    "503" => "Service Unavailable"
  }

  @mime_table = [
    TEXT_CONTENT,
    HTML_CONTENT,
    JSON_CONTENT
  ]

  @status = "200"
  @header = {}
  @content_type = HTML_CONTENT
  @body = ""
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



2
3
4
# File 'lib/amber/http/response.rb', line 2

def body
  @body
end

#content_typeObject

Returns the value of attribute content_type.



2
3
4
# File 'lib/amber/http/response.rb', line 2

def content_type
  @content_type
end

#headerObject

Returns the value of attribute header.



2
3
4
# File 'lib/amber/http/response.rb', line 2

def header
  @header
end

#statusObject

Returns the value of attribute status.



2
3
4
# File 'lib/amber/http/response.rb', line 2

def status
  @status
end

Instance Method Details

#create_status_lineObject



50
51
52
53
54
55
56
57
# File 'lib/amber/http/response.rb', line 50

def create_status_line
  status_line = "HTTP/1.1 "
  status_line << @status
  status_line << ' '
  status_line << @status_table[@status]
  status_line << "\r\n"
  status_line
end

#sendObject



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/amber/http/response.rb', line 37

def send
  data = create_status_line
  data << "Server: Amber/0.0.1\r\n"
  @header.each do |key, value|
    data << "#{key}: #{value}\r\n"
  end
  data << "Content-Type: #{@content_type}\r\n"
  data << "Content-Length: #{@body.length}\r\n\r\n"
  data << @body

  @socket.sendmsg data, 0
end