Skip to content

Commit

Permalink
Add ruby-based web redirector code
Browse files Browse the repository at this point in the history
  • Loading branch information
thierryr committed Feb 23, 2015
1 parent 35703e8 commit 24942a6
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
10 changes: 10 additions & 0 deletions gec22_demo/web_redirector/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Thanks to @minhajuddin for the template
# http://minhajuddin.com/2010/06/06/redirector-a-simple-rack-application-which-makes-redirection-of-multiple-domains-a-breeze

# Install Ruby Rack

gem install rack --no-ri --no-rdoc

# Run with:

rackup -o IP_of_your_server config.ru
11 changes: 11 additions & 0 deletions gec22_demo/web_redirector/config.ru
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
require './redirector'

use Rack::ContentLength

app = proc do |env|
app = Redirector.new()
status, headers, response = app.call(env)
[ status, headers, response ]
end

run app
19 changes: 19 additions & 0 deletions gec22_demo/web_redirector/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# NO CIDR NOTATION SUPPORT!!!
# Convention:
# - net_A_B_C_D for the network IP address A.B.C.D
# - net_A_B_C for the network IP address A.B.C.0
# - net_A_B for the network IP address A.B
# - net_A for the network IP address A
# - default for everyting else
#
net_10_15:
status: 303
location: 'http://www.nicta.com.au'

net_203_143_174:
status: 303
location: 'http://www.w3.org'

default:
status: 303
location: 'http://www.google.com.au'
34 changes: 34 additions & 0 deletions gec22_demo/web_redirector/redirector.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Thanks to @minhajuddin for the template
# http://minhajuddin.com/2010/06/06/redirector-a-simple-rack-application-which-makes-redirection-of-multiple-domains-a-breeze
#
require 'yaml'

class Redirector

PREFIX = "net_"
@@config = YAML::load(File.open('config.yaml'))

def self.config
@@config
end

def call(env)
redirect_info = get_redirect_info(env['REMOTE_ADDR'])
puts "-- #{Time.now} -- Host: #{env['REMOTE_ADDR']} -- Redirect: #{redirect_info['location']}"
[redirect_info['status'], {'Content-Type' => 'text','Location' => redirect_info['location']}, get_host_response( redirect_info ) ]
#['200', {'Content-Type' => 'text/html'}, ['get rack\'d']]
end

private
def get_host_response(redirect_info)
["#{redirect_info['status']} moved. The document has moved to #{redirect_info['location']}"]
end

def get_redirect_info(host)
(0..3).each do |i|
net = PREFIX+host.split('.')[0,(4-i)].join('_')
return @@config[net] unless @@config[net].nil?
end
return @@config['default']
end
end

0 comments on commit 24942a6

Please sign in to comment.