Class: SimpleProxy::App

Inherits:
Sinatra::Base
  • Object
show all
Defined in:
lib/simple_proxy.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.quit!Object

stop the server



108
109
110
111
112
113
114
115
116
# File 'lib/simple_proxy.rb', line 108

def self.quit!
  if File.exist?('simple_proxy.pid')
    pid = File.read('simple_proxy.pid').to_i
    Process.kill("TERM", pid)
    File.delete('simple_proxy.pid')
  else
    puts "No running instance found"
  end
end

.run!Object

start the server



98
99
100
101
102
103
104
105
# File 'lib/simple_proxy.rb', line 98

def self.run!
  pid = Process.fork do
    $stderr.reopen(File.new('/dev/null', 'w'))
    $stdout.reopen(File.new('/dev/null', 'w'))
    super()
  end
  File.write('simple_proxy.pid', pid)
end

Instance Method Details

#extract_request_headersObject



84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/simple_proxy.rb', line 84

def extract_request_headers
  headers = {}
  env.each do |key, value|
    # HTTP_HEADER_NAME format is how Rack sends headers
    if key.start_with?('HTTP_') && !['HTTP_VERSION', 'HTTP_HOST'].include?(key)
      # Convert HTTP_HEADER_NAME to Header-Name
      header_name = key[5..-1].split('_').collect(&:capitalize).join('-')
      headers[header_name] = value
    end
  end
  headers
end

#proxy_request(method) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/simple_proxy.rb', line 60

def proxy_request(method)
  target_url = params['url']

  # Remove 'url' from params to avoid sending it in the query parameters
  params.delete('url')

  options = {
    query: params, # Send remaining params as query parameters
    headers: extract_request_headers
  }

  if [:post, :put].include?(method)
    options[:body] = request.body.read
    options[:headers]['Content-Type'] = 'application/json'
  end

  response = HTTParty.send(method, target_url, options)

  content_type response.headers['content-type']
  headers 'Accept-all' => 'true' # Add the Accept-all header to the response

  response.body
end