Class: Async::HTTP::Server

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Server.



21
22
23
24
25
26
27
# File 'lib/async/http/server.rb', line 21

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.



41
42
43
# File 'lib/async/http/server.rb', line 41

def endpoint
  @endpoint
end

#protocolObject (readonly)

Returns the value of attribute protocol.



42
43
44
# File 'lib/async/http/server.rb', line 42

def protocol
  @protocol
end

#schemeObject (readonly)

Returns the value of attribute scheme.



43
44
45
# File 'lib/async/http/server.rb', line 43

def scheme
  @scheme
end

Class Method Details

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



17
18
19
# File 'lib/async/http/server.rb', line 17

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

Instance Method Details

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



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/async/http/server.rb', line 45

def accept(peer, address, task: Task.current)
	connection = @protocol.server(peer)
	
	Console.logger.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
		
		# This is a slight optimization to avoid having to get the address from the socket.
		request.remote_address = address
		
		# Console.logger.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



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

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

#runObject



68
69
70
71
72
73
74
75
# File 'lib/async/http/server.rb', line 68

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

#to_jsonObject



37
38
39
# File 'lib/async/http/server.rb', line 37

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