Class: Adelnor::BaseServer
- Inherits:
-
Object
- Object
- Adelnor::BaseServer
show all
- Defined in:
- lib/adelnor/base_server.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(rack_app, port, options = {}) ⇒ BaseServer
Returns a new instance of BaseServer.
12
13
14
15
16
17
18
19
20
21
22
23
|
# File 'lib/adelnor/base_server.rb', line 12
def initialize(rack_app, port, options = {})
@rack_app = rack_app
@port = port
@options = options
@socket = Socket.new(:INET, :STREAM)
addr = Socket.sockaddr_in(@port, '0.0.0.0')
@socket.bind(addr)
@socket.listen(2)
puts welcome_message
end
|
Class Method Details
.run(*args) ⇒ Object
25
26
27
|
# File 'lib/adelnor/base_server.rb', line 25
def self.run(*args)
new(*args).run
end
|
Instance Method Details
#handle(client) ⇒ Object
51
52
53
54
55
56
57
58
59
|
# File 'lib/adelnor/base_server.rb', line 51
def handle(client)
read_request_message(client)
.then { |message| Request.build(message) }
.tap { |request| request.parse_body!(client) }
.then { |request| rack_data(request) }
.then { |data| @rack_app.call(data) }
.then { |result| Response.build(*result) }
.then { |response| client.puts(response) }
end
|
#rack_data(request) ⇒ Object
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/adelnor/base_server.rb', line 29
def rack_data(request)
{
'REQUEST_METHOD' => request.request_method,
'PATH_INFO' => request.path_info,
'QUERY_STRING' => request.query_string,
'SERVER_PORT' => @port,
'SERVER_NAME' => request.['Host'],
'CONTENT_LENGTH' => request.content_length,
'HTTP_COOKIE' => request.['Cookie'],
'rack.input' => StringIO.new(request.body)
}.merge(request.)
end
|
#read_request_message(client) ⇒ Object
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# File 'lib/adelnor/base_server.rb', line 61
def read_request_message(client)
message = ''
if (line = client.gets)
message += line
end
puts "\n[#{Time.now}] #{message}"
while (line = client.gets)
break if line == "\r\n"
message += line
end
message
end
|
#run ⇒ Object
42
43
44
45
46
47
48
49
|
# File 'lib/adelnor/base_server.rb', line 42
def run
loop do
client, = @socket.accept
handle(client)
client.close
end
end
|
#welcome_message ⇒ Object
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
# File 'lib/adelnor/base_server.rb', line 79
def welcome_message
thread_pool_message = "Running with thread pool of #{@options[:thread_pool]} threads" if @options[:thread_pool]
<<~WELCOME
|\---/|
| o_o |
\_^_/
adelnor HTTP server
------------------------------------------------
Adelnor is running at http://0.0.0.0:#{@port}
Listening to HTTP connections
#{thread_pool_message}
WELCOME
end
|