forked from ciaranlee/geoip_sinatra
-
Notifications
You must be signed in to change notification settings - Fork 1
/
geo.rb
58 lines (50 loc) · 1.27 KB
/
geo.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require 'rubygems'
require 'cgi'
require "bundler"
Bundler.setup
require 'rack'
require 'sinatra'
require "sinatra/reloader" if development?
require 'json'
require 'geoip'
require 'rack/contrib/jsonp'
use Rack::JSONP
configure :production do
require 'newrelic_rpm'
end
configure do
GEOIP = GeoIP.new('GeoLiteCity.dat')
end
get '/' do
'try something like /location.json?ip=134.226.83.50 to check a specific IP or /locateme.json to geocode your own IP'
end
get '/location.json' do
callback = params.delete('callback')
returnable = {:message => "you didn't supply an IP to geocode!"}
returnable = GEOIP.city(params[:ip]).to_hash if params[:ip]
json = returnable.to_json
if callback
content_type :js, :charset => "utf-8"
response = "#{callback}(#{json})"
else
content_type :json, :charset => "utf-8"
response = json
end
response
end
get '/locateme.json' do
callback = params.delete('callback')
returnable = {:message => "your IP could not be geocoded"}
if geoip_result = GEOIP.city(request.ip)
returnable = geoip_result.to_hash
end
json = returnable.to_json
if callback
content_type :js, :charset => "utf-8"
response = "#{callback}(#{json})"
else
content_type :json, :charset => "utf-8"
response = json
end
response
end