require 'ritm' require 'json' require 'cert' module Doraemon class ProxyServer def initialize(port=8000, root) @port = port @root = root end 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 end end