NetX :: HTTPUnixを使ってUnixソケットを使ってHTTP要求を行うために、カスタムのファラデーアダプタをまとめてみました。コードは次のようになります。ファラデーを使ってUnixソケット経由でHTTPリクエストを作成する
module Faraday
class Adapter
class NetHttpUnix < Faraday::Adapter::NetHttp
def perform_request(http, env)
if :get == env[:method] and !env[:body]
# prefer `get` to `request` because the former handles gzip (ruby 1.9)
http.get env[:url], env[:request_headers]
else
http.request create_request(env)
end
end
def create_request(env)
request = Net::HTTPGenericRequest.new \
env[:method].to_s.upcase, # request method
!!env[:body], # is there request body
:head != env[:method], # is there response body
"/", # request uri path (i'm just hard coding/because URI::Generic doesn't have a uri_path method
env[:request_headers] # request headers
if env[:body].respond_to?(:read)
request.body_stream = env[:body]
else
request.body = env[:body]
end
request
end
def net_http_connection(env)
socket = env[:url].to_s
NetX::HTTPUnix.new(socket)
end
end
end
end
Faraday::Adapter.register_middleware net_http_unix: Faraday::Adapter::NetHttpUnix
ただし、このアダプタでリクエストを行うと、私はFaraday :: ConnectionErrorを取得します。例外のバックトレースを見ると、コードがhttp.rbのTCPソケットを開こうとしているのがわかります。
すでにUnixソケットで動作するファラデーアダプタがありますか?私はここで車輪を再発明したくない。
引数を複数の行に分割する場合は、それらをカプセル化するために、通常の角括弧 '(...) 'を使用します。ここのバックスラッシュは非常に不規則です。 – tadman