Skip to content

Commit

Permalink
Add HTTP::Server::Context#socket
Browse files Browse the repository at this point in the history
This allows to determine the client connection when a `HTTP::Server` binds
to multiple interfaces.
  • Loading branch information
straight-shoota committed Mar 6, 2018
1 parent bd3f308 commit f88addb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
7 changes: 6 additions & 1 deletion spec/std/http/server/server_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,11 @@ module HTTP

it "binds to different ports" do
server = Server.new do |context|
context.response.print "Test Server (#{context.request.headers["Host"]?})"
socket = context.socket
socket.should be_a(TCPSocket)
if socket.is_a? TCPSocket
context.response.print "Test Server (127.0.0.1:#{socket.local_address.port})"
end
end

tcp_server = TCPServer.new(0)
Expand All @@ -266,6 +270,7 @@ module HTTP
processor = HTTP::Server::RequestProcessor.new do |context|
context.response.content_type = "text/plain"
context.response.print "Hello world"
context.socket.should be_nil
end

input = IO::Memory.new("GET / HTTP/1.1\r\n\r\n")
Expand Down
5 changes: 4 additions & 1 deletion src/http/server/context.cr
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ class HTTP::Server
# The `HTTP::Server::Response` to configure and write to.
getter response : Response

# An optional `Socket` which holds the client connection of this context.
getter socket : Socket?

# :nodoc:
def initialize(@request : Request, @response : Response)
def initialize(@request : Request, @response : Response, @socket : Socket? = nil)
end
end
end
7 changes: 6 additions & 1 deletion src/http/server/request_processor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ class HTTP::Server::RequestProcessor
response.version = request.version
response.reset
response.headers["Connection"] = "keep-alive" if request.keep_alive?
context = Context.new(request, response)

if input.is_a?(Socket)
context = Context.new(request, response, input)
else
context = Context.new(request, response)
end

begin
@handler.call(context)
Expand Down

0 comments on commit f88addb

Please sign in to comment.