Ruby 使用法拉第通过Unix套接字发出HTTP请求
我试着组装一个定制的法拉第适配器,使用一个使用NetX::HTTPUnix的Unix套接字发出HTTP请求。代码如下所示:Ruby 使用法拉第通过Unix套接字发出HTTP请求,ruby,faraday,unix-socket,Ruby,Faraday,Unix Socket,我试着组装一个定制的法拉第适配器,使用一个使用NetX::HTTPUnix的Unix套接字发出HTTP请求。代码如下所示: module Faraday class Adapter class NetHttpUnix < Faraday::Adapter::NetHttp def perform_request(http, env) if :get == env[:method] and !env[:body] # prefer
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
法拉第模块
类适配器
类NetHttpUnix
然而,当我尝试使用这个适配器发出请求时,我得到了一个法拉第::ConnectionError。当我查看异常回溯时,我看到代码试图在http.rb中打开TCP套接字
是否已经有一个法拉第适配器可以与Unix套接字一起工作?我不想在这里重新发明轮子。仔细研究后,上面的代码实际上非常好 由于Ruby的
URI.parse的工作原理,我遇到了一些问题。我的URI是unix:///path/to/socket
,它URI.parse
解析到unix:/path/to/socket
,而Net::Http::unix又没有解析为unix套接字URL,因为它希望unix套接字URI以unix://
开头>
解决方案是在我的路径中使用五个斜杠,如下所示:unix://///path/to/socket
。执行此操作时,URI.parse
将其解析为unix:///path/to/socket
,net\u http\u unix
看到它以unix://
开头,并去掉该部分,留下我们可以使用的/path/to/socket
n连接到
在我的例子中,我指定了一个绝对路径;如果我使用的是相对路径,我可能对unix://relative/path/to/socket
关于我上面的代码有一个警告:Net::httpgenerirequest.new
的第四个参数只是“/”。这对我来说很合适,因为我使用的RPC over HTTP从来没有相对URI;如果你的应用程序或服务中有相对URI,你需要一种方法来获取URI并将套接字路径与相对路径分开。如果你要在几行上拆分参数,请使用常规括号(…)
来封装它们。这里的反斜杠是非常不规则的。我们有两个选项来解决这个问题:1)修复UNIX\u REGEXP in-为file://添加测试,或2)修复(或monkey patch)URI,因为它只知道file://和postgres://所以可以对ruby repo进行PR