Class: Doraemon::ProxyServer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port = 7000, scene_id) ⇒ ProxyServer

Returns a new instance of ProxyServer.



17
18
19
20
21
# File 'lib/doraemon/proxy_server.rb', line 17

def initialize(port=7000, scene_id)
  @port = port
  @scene_id = scene_id
  @mutex = Mutex.new
end

Instance Attribute Details

#scene_idObject

Returns the value of attribute scene_id.



15
16
17
# File 'lib/doraemon/proxy_server.rb', line 15

def scene_id
  @scene_id
end

Instance Method Details

#startObject



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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/doraemon/proxy_server.rb', line 23

def start()
  
  Cert.generate_cert

  puts "Proxy server start, port: #{@port}, scene_id: #{@scene_id}"

  _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
    ssl_reverse_proxy[:bind_port] = _port + 10000;
    proxy[:bind_address] = '0.0.0.0'
    proxy[:bind_port] = _port
  end
  
  _session.on_response do |_req, _resp|

    # NOTE: 这里每次回调会在单独线程进行
    next unless _req.request_uri.host.end_with?('idongjia.cn')

    _params = begin JSON.parse(_req.body) rescue _req.body end
    _result = begin JSON.parse(_resp.body) rescue {} end

    if @scene_id > 0
      _path = _req.path
      DB.query_api_contents(@scene_id, _path) do |api|
        if !api.nil?
          _resp_body = nil
          begin
            _result = eval(api['contents'])
            _resp_body = _result.to_json
          rescue Exception => e
            puts "Exception rescue: #{e.full_message(order: :top)}"
            _result = {
              "code": -1,
              "msg": "#{_path} 处理错误: #{e.to_s}"
            }
            _resp_body = _result.to_json
          end

          _resp.status = 200
          _resp.body = _resp_body
          _resp.header['content-length'] = _resp.body.bytesize
          _resp.header['content-type'] = 'application/json; charset=utf-8'

          puts "-----------------------------------------------------------------"
          puts "  - PATH: #{_req.request_uri}"
          puts "  - Request: #{_params.to_json}"
          puts "  - Response: #{_resp_body}"
        end
      end
    end

  end
  
  _session.start

  trap 'INT' do
    _session.shutdown
    return
  end
  loop { gets }
end