Class: Doraemon::ProxyServer

Inherits:
Object
  • Object
show all
Defined in:
lib/doraemon/proxy_server.rb

Instance Method Summary collapse

Constructor Details

#initialize(port = 8000, root) ⇒ ProxyServer

Returns a new instance of ProxyServer.



9
10
11
12
# File 'lib/doraemon/proxy_server.rb', line 9

def initialize(port=8000, root)
  @port = port
  @root = root
end

Instance Method Details

#start(api_list) ⇒ Object



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
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/doraemon/proxy_server.rb', line 14

def start(api_list)
  
  Cert.generate_cert

  session = Ritm::Session.new

  port = @port
  
  session.configure do
    ssl_reverse_proxy.ca[:pem] = Cert.cert_path
    ssl_reverse_proxy.ca[:key] = Cert.key_path
    proxy[:bind_address] = '0.0.0.0'
    proxy[:bind_port] = port
  end
  
  session.on_response do |_req, _resp|

    if api_list.include?(_req.path)

      _params = nil
      begin
        _params = JSON.parse(_req.body)
      rescue
        _params = _req.body
      end

      _result = JSON.parse(_resp.body)

      begin
        _result = eval(File.read(File.join(@root, api_list[_req.path])))
      rescue
        _result = {
          "code": -1,
          "msg": "#{_req.path} 处理错误"
        }
      end
      
      _resp.status = 200
      _resp.body = _result.to_json
      _resp.header['content-length'] = _resp.body.bytesize
      _resp.header['content-type'] = 'application/json;charset=UTF-8'
      
      puts "- - - > #{_req.path}"
      puts "#{JSON.pretty_generate(_result)}\n\n"
    end
    
  end
  
  session.start
  
  # trap 'INT' do
  #   session.shutdown
  #   return
  # end
  # loop { gets }

end