support unix socket request

This commit is contained in:
邱博亞 2023-04-02 21:53:52 +08:00
parent 848d5e6714
commit b5a297e875
2 changed files with 15 additions and 16 deletions

View File

@ -1,7 +1,7 @@
# frozen_string_literal: true
require 'faraday'
require 'roda/proxy/version'
require 'net_http_unix'
# :nodoc:
class Roda
@ -35,8 +35,11 @@ class Roda
# rewritten to be the destination host. The response headers, body and
# status are returned to the client.
def proxy
method = Faraday.method(env['REQUEST_METHOD'].downcase.to_sym)
f_response = method.call(_proxy_url) { |req| _proxy_request(req) }
client = NetX::HTTPUnix.new(_sock_url)
request_class = Net::HTTP.const_get(:"#{env['REQUEST_METHOD'].to_s.downcase.capitalize}")
req = request_class.new(_proxy_url.to_s, _proxy_headers)
f_response = client.request(req)
# p f_response
_respond(f_response)
end
@ -63,12 +66,13 @@ class Roda
private
def _sock_url
roda_class.opts[:proxy_to]
end
def _proxy_url
@_proxy_url ||= URI(roda_class.opts[:proxy_to])
.then { |uri| uri.path = roda_class.opts[:proxy_path]; uri } # prefix
.then { |uri| uri.path += env['PATH_INFO'][1..-1]; uri } # path
.then { |uri| uri.query = env['QUERY_STRING']; uri }
uri = URI("#{roda_class.opts[:proxy_path]}#{env['PATH_INFO'][1..-1]}")
uri.query = env['QUERY_STRING']
uri
end
def _proxy_headers
@ -82,15 +86,11 @@ class Roda
.join('-')
end
.merge({
'Host' => "#{_proxy_url.host}:#{_proxy_url.port}",
'Host' => "localhost",
'Via' => _via_header_string
})
end
def _proxy_request(req)
req.headers = _proxy_headers
end
def _respond(proxied_response)
response.status = proxied_response.status
proxied_response

View File

@ -12,7 +12,7 @@ Gem::Specification.new do |spec|
spec.description = 'A very simple reverse proxy for Roda'
spec.homepage = 'https://github.com/BillyRuffian/roda-proxy'
spec.license = 'MIT'
spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
spec.required_ruby_version = Gem::Requirement.new('>= 2.1.0')
spec.metadata['allowed_push_host'] = 'https://rubygems.org'
@ -29,7 +29,6 @@ Gem::Specification.new do |spec|
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_dependency 'faraday', '~> 1.0'
spec.add_dependency 'roda', '~> 3.0'
spec.add_development_dependency 'rerun', '~> 0.13'