Skip to content

Commit

Permalink
Add HTTP::Server#bind_unix (#5959)
Browse files Browse the repository at this point in the history
* Add HTTP::Server#bind_unix

* fixup! Add HTTP::Server#bind_unix
  • Loading branch information
straight-shoota authored and RX14 committed Apr 18, 2018
1 parent 01a5126 commit aa596d3
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
48 changes: 48 additions & 0 deletions spec/std/http/server/server_spec.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
require "spec"
require "http/server"
require "http/client/response"
require "tempfile"

private class RaiseErrno < IO
def initialize(@value : Int32)
Expand Down Expand Up @@ -40,6 +42,16 @@ private class ReverseResponseOutput < IO
end
end

# TODO: replace with `HTTP::Client` once it supports connecting to Unix socket (#2735)
private def unix_request(path)
UNIXSocket.open(path) do |io|
request = HTTP::Request.new("GET", "/", HTTP::Headers{"X-Unix-Socket" => path})
request.to_io(io)

HTTP::Client::Response.from_io(io).body
end
end

module HTTP
class Server
describe Response do
Expand Down Expand Up @@ -310,6 +322,42 @@ module HTTP
end
end
end

{% if flag?(:unix) %}
describe "#bind_unix" do
it "binds to different unix sockets" do
path1 = Tempfile.tempname
path2 = Tempfile.tempname

begin
server = Server.new do |context|
# TODO: Replace custom header with local_address (#5784)
context.response.print "Test Server (#{context.request.headers["X-Unix-Socket"]?})"
context.response.close
end

socket1 = UNIXServer.new(path1)
server.bind socket1
socket2 = server.bind_unix path2

spawn server.listen

Fiber.yield

unix_request(path1).should eq "Test Server (#{path1})"
unix_request(path2).should eq "Test Server (#{path2})"

server.close

File.exists?(path1).should be_false
File.exists?(path2).should be_false
ensure
File.delete(path1) if File.exists?(path1)
File.delete(path2) if File.exists?(path2)
end
end
end
{% end %}
end

describe HTTP::Server::RequestProcessor do
Expand Down
14 changes: 14 additions & 0 deletions src/http/server.cr
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,20 @@ class HTTP::Server
bind_tcp host, 0, reuse_port
end

# Creates a `UNIXServer` bound to *path* and adds it as a socket.
#
# ```
# server = HTTP::Server.new { }
# server.bind_unix "/tmp/my-socket.sock"
# ```
def bind_unix(path : String) : Socket::UNIXAddress
server = UNIXServer.new(path)

bind(server)

server.local_address
end

# Adds a `Socket::Server` *socket* to this server.
def bind(socket : Socket::Server) : Nil
raise "Can't add socket to running server" if listening?
Expand Down

0 comments on commit aa596d3

Please sign in to comment.