Skip to content

Instantly share code, notes, and snippets.

@samueleaton
Created March 15, 2019 00:20
Show Gist options
  • Save samueleaton/0324e4b16702de39dc61de3ab9538032 to your computer and use it in GitHub Desktop.
Save samueleaton/0324e4b16702de39dc61de3ab9538032 to your computer and use it in GitHub Desktop.
Adds remote_address to server context
require "http/server"
# from https://github.com/crystal-lang/crystal/pull/7302
class HTTP::Request
@io : IO?
def initialize(@method : String, @resource : String, headers : Headers? = nil, body : String | Bytes | IO | Nil = nil, @version = "HTTP/1.1", @io : IO? = nil)
@headers = headers.try(&.dup) || Headers.new
self.body = body
end
def self.from_io(io)
request_line = io.gets(4096, chomp: true)
return unless request_line
parts = request_line.split
return BadRequest.new unless parts.size == 3
method, resource, http_version = parts
return BadRequest.new unless HTTP::SUPPORTED_VERSIONS.includes?(http_version)
HTTP.parse_headers_and_body(io) do |headers, body|
return new method, resource, headers, body, http_version, io
end
# Malformed or unexpectedly ended http request
BadRequest.new
end
def remote_address
if (io = @io).responds_to?(:remote_address)
io.remote_address
else
raise "#{io} doesn't have a remote address"
end
end
def remote_address?
if (io = @io).responds_to?(:remote_address)
io.remote_address
end
end
end
class OpenSSL::SSL::Socket
def remote_address
if (io = @bio.io).responds_to?(:remote_address)
io.remote_address
else
raise "#{io} doesn't have a remote address"
end
end
def remote_address?
if (io = @bio.io).responds_to?(:remote_address)
io.remote_address
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment