pope (owner)

Revisions

gist: 170150 Download_button fork
public
Public Clone URL: git://gist.github.com/170150.git
Embed All Files: show embed
host_ip_info_service.ru #
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
require "eventmachine"
 
# Load this script up with thin
 
class DeferrableBody
  include EventMachine::Deferrable
 
  def call(body)
    body.each do |chunk|
      @body_callback.call(chunk)
    end
  end
 
  def each &blk
    @body_callback = blk
  end
end
 
class AsyncHostIPInfo
  AsyncResponse = [-1, {}, []].freeze
 
  def call(env)
    body = DeferrableBody.new
    req = Rack::Request.new(env)
 
    EM::next_tick do
      env['async.callback'].call [200, {'Content-Type' => 'text/javascript'}, body]
    end
 
    ip = req.params["ip"]
    callback = req.params["callback"]
 
    conn = EM::Protocols::HttpClient2.connect "api.hostip.info", 80
    http = conn.get "/get_html.php?ip=#{ip}&position=true"
    http.callback do |r|
      contents = r.content.split("\n").map do |line|
        if line =~ /^C(ountry|ity)/
          line.gsub(/(.*): (.*)/, '\1:"\2"')
        else
          line.sub(": ", ":")
        end
      end
      body.call ["#{callback}({#{contents.join(",")}});"]
      body.succeed
    end
 
    AsyncResponse
  end
end
 
run AsyncHostIPInfo.new