Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra app that redirects POST/GET requests with parameters

I'm migrating servers but unfortunately the old server IP is hardcoded inside my iPhone app. Obviously I'm going to submit an update that sets the API endpoint to my new server, but in the meantime I need to setup an app on the old server that redirects all the requests to the new server. I've heard Sinatra would be perfect for this.

require 'sinatra'

get "/foo/bar" do
    redirect "http://new-server.com/foo/bar", 303
end

post "/foo/bar" do
    redirect "http://new-server.com/foo/bar", 303
end

The problem is that these do not forward the GET or POST parameters along with the request. I read on the Sinatra doc that you can do that by putting them in the URL directly (works for GET requests), or by setting session variables.

Is manually parsing and formatting the GET params to put them back into the redirect URL the only way to go for GET redirects? How are you supposed to forward POST parameters?

like image 275
samvermette Avatar asked Aug 12 '12 07:08

samvermette


2 Answers

For GET requests, use request.fullpath or request.query_string. For POST request, use status code 307, so the subsequent request will be a POST with the same parameters.

helpers do
  def new_url
    "http://new-server.com" + request.fullpath
  end
end

get "/foo/bar" do
  redirect new_url
end

post "/foo/bar" do
  redirect new_url, 307
end
like image 158
Konstantin Haase Avatar answered Nov 12 '22 15:11

Konstantin Haase


I would overload the Hash class in lib/overload_hash.rb, like so:

class Hash
  def to_url_params
    elements = []
    keys.size.times do |i|
      elements << "#{keys[i]}=#{values[i]}"
    end
    elements.join('&')
  end
end

EDIT (Better solution using net / http)

Place a require "lib/overload_hash", require "net/http" and require "uri" under require 'sinatra'. The following example can be translated into GET easily.

post '/foo/bar' do
  uri = URI.parse("http://example.com/search")
  response = Net::HTTP.post_form(uri, params.to_ur_params) 
  response
end
like image 2
briangonzalez Avatar answered Nov 12 '22 15:11

briangonzalez