Class: Async::HTTP::Server

Inherits:
Protocol::HTTP::Middleware
  • Object
show all
Defined in:
lib/async/http/server.rb

Overview

An HTTP server that accepts connections on a specific endpoint and dispatches requests to an application handler.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, endpoint, protocol: endpoint.protocol, scheme: endpoint.scheme) ⇒ Server

Initialize the server with an application handler and endpoint.



29
30
31
32
33
34
35
# File 'lib/async/http/server.rb', line 29

def initialize(app, endpoint, protocol: endpoint.protocol, scheme: endpoint.scheme)
	super(app)
	
	@endpoint = endpoint
	@protocol = protocol
	@scheme = scheme
end

Instance Attribute Details

#endpointObject (readonly)

Returns the value of attribute endpoint.



51
52
53
# File 'lib/async/http/server.rb', line 51

def endpoint
  @endpoint
end

#protocolObject (readonly)

Returns the value of attribute protocol.



52
53
54
# File 'lib/async/http/server.rb', line 52

def protocol
  @protocol
end

#schemeObject (readonly)

Returns the value of attribute scheme.



53
54
55
# File 'lib/async/http/server.rb', line 53

def scheme
  @scheme
end

Class Method Details

.for(*arguments, **options, &block) ⇒ Object

Create a server using a block as the application handler.



20
21
22
# File 'lib/async/http/server.rb', line 20

def self.for(*arguments, **options, &block)
	self.new(block, *arguments, **options)
end

Instance Method Details

#accept(peer, address, task: Task.current) ⇒ Object

Accept an incoming connection and process requests.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/async/http/server.rb', line 58

def accept(peer, address, task: Task.current)
	connection = @protocol.server(peer)
	
	Console.debug(self){"Incoming connnection from #{address.inspect} to #{@protocol}"}
	
	connection.each do |request|
		# We set the default scheme unless it was otherwise specified.
		# https://tools.ietf.org/html/rfc7230#section-5.5
		request.scheme ||= self.scheme
		
		# Console.debug(self) {"Incoming request from #{address.inspect}: #{request.method} #{request.path}"}
		
		# If this returns nil, we assume that the connection has been hijacked.
		self.call(request)
	end
ensure
	connection&.close
end

#as_jsonObject



38
39
40
41
42
43
44
# File 'lib/async/http/server.rb', line 38

def as_json(...)
	{
		endpoint: @endpoint.to_s,
		protocol: @protocol,
		scheme: @scheme,
	}
end

#runObject



78
79
80
81
82
83
84
85
# File 'lib/async/http/server.rb', line 78

def run
	Async do |task|
		@endpoint.accept(&self.method(:accept))
		
		# Wait for all children to finish:
		task.children.each(&:wait)
	end
end

#to_jsonObject



47
48
49
# File 'lib/async/http/server.rb', line 47

def to_json(...)
	as_json.to_json(...)
end