From aa596d32b7c900283eb6a4ab4727891c8177ad79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Wed, 18 Apr 2018 16:19:45 +0200 Subject: [PATCH] Add HTTP::Server#bind_unix (#5959) * Add HTTP::Server#bind_unix * fixup! Add HTTP::Server#bind_unix --- spec/std/http/server/server_spec.cr | 48 +++++++++++++++++++++++++++++ src/http/server.cr | 14 +++++++++ 2 files changed, 62 insertions(+) diff --git a/spec/std/http/server/server_spec.cr b/spec/std/http/server/server_spec.cr index c0c562433704..ffd157725db3 100644 --- a/spec/std/http/server/server_spec.cr +++ b/spec/std/http/server/server_spec.cr @@ -1,5 +1,7 @@ require "spec" require "http/server" +require "http/client/response" +require "tempfile" private class RaiseErrno < IO def initialize(@value : Int32) @@ -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 @@ -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 diff --git a/src/http/server.cr b/src/http/server.cr index b038a2fe9ab3..a792cfe0aadc 100644 --- a/src/http/server.cr +++ b/src/http/server.cr @@ -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?