require 'ritm' require 'json' require 'cert' module Doraemon class ProxyServer def initialize(port=8000, root) @port = port @root = root end def start() 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| puts "-----------------------------------------------------------------" puts " - URI: #{_req.request_uri}" name = _req.path if name.start_with?('/') name = name[1, name.size - 1] end name = name.gsub('_', '__').gsub('/', '_') _api_path = nil for ext in [".rb", ".json", ".api"] do path = File.join(@root, "#{name}#{ext}") if File.exist?(path) _api_path = path break end end _params = begin JSON.parse(_req.body) rescue _req.body end _result = begin JSON.parse(_resp.body) rescue {} end if _api_path begin _result = eval(File.read(_api_path)) if File.exist?(_api_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' end print_req_body = false print_resp_body = false req_content_type = _req.header['content-type'] ["text", "json"].each do | t | if req_content_type.class == Array req_content_type.each do | tt | if tt.downcase.index(t) != nil print_req_body = true end end end if _resp.header['content-type'].downcase.index(t) != nil print_resp_body = true end end if print_req_body puts " - Request: #{_req.body}\n" else if _req.body.class != NilClass puts " - Response: <#{_req.body.length}>" end end if print_resp_body puts " - Response: #{_resp.body}\n" if print_resp_body else if _resp.body.class != NilClass puts " - Response: <#{_resp.header['content-type']}>, size #{_resp.body.length}" end end puts "\n" end _session.start # trap 'INT' do # _session.shutdown # return # end # loop { gets } end end end