Last active
July 20, 2020 08:55
-
-
Save RaVbaker/d9ead3c92b915f997dab25c7f0c0ab65 to your computer and use it in GitHub Desktop.
Simple HTTP app Proxy using sinatra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ENDPOINT="host.com" ruby app_proxy.rb | |
# curl -i localhost:4567/capture # => "<TIMEOUT>" or regular response every 2 calls | |
require 'sinatra' | |
require 'net/http' | |
$request_settings = { host: ENV["ENDPOINT"] } | |
$headers = { "Content-Type" => "application/json" } | |
$counter = 0 | |
# define halts | |
$might_timeout = -> (request) { request.path_info =~ /preauthorization/ } | |
# methods | |
def api_request(type, path, query_string, body, new_headers) | |
uri = URI::HTTP.build( | |
$request_settings.merge( | |
path: path, | |
query: query_string, | |
) | |
) | |
req = Net::HTTP.const_get(type).new(uri, $headers.merge(new_headers)) | |
req.body = body.read | |
Net::HTTP.new(uri.hostname, uri.port).start {|http| http.request(req) } | |
end | |
def all_headers(response) | |
header_list = {} | |
response.header.each_capitalized do |k,v| | |
header_list[k] =v unless k == "Transfer-Encoding" | |
end | |
header_list | |
end | |
def incomming_headers(request) | |
request.env.map { |header, value| [header[5..-1].split("_").map(&:capitalize).join('-'), value] if header.start_with?("HTTP_") }.compact.to_h | |
end | |
# wildcard routing | |
%w(get post put patch delete).each do |verb| | |
send(verb, /.*/) do | |
content_type $headers["Content-Type"] | |
start_request = Thread.new { | |
api_request(verb.capitalize, request.path_info, request.query_string, request.body, incomming_headers(request)) | |
} | |
if $might_timeout.call(request) | |
$counter += 1 | |
halt(404, "<TIMEOUT>") if ($counter % 2).zero? | |
end | |
response = start_request.value | |
status response.code | |
headers all_headers(response) | |
response.body | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment