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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
# File 'lib/webfx.rb', line 54
def run_app(env)
begin
request = Rack::Request.new(env)
def static(type, file)
[200, { 'Content-Type' => type, 'Cache-Control' => 'public, max-age=86400' }, File.read(file)]
end
if request.path == '/'
return [200, { 'Content-Type' => 'text/html', 'Content-Encoding' => 'gzip' }, index_html]
end
if request.path.match(/(.*).js$/)
return static('text/javascript', "public/#{$1}.js")
end
if request.path.match(/(.*).css$/)
return static('text/css', "public/#{$1}.css")
end
if request.path.match(/(images\/.*).png$/)
return static('image/png', "public/#{$1}.png")
end
if request.path.match(/(images\/.*).jpg$/)
return static('image/jpg', "public/#{$1}.jpg")
end
params = request.params
if request.post?
if not params['file']
body = request.body.read
params.merge!(JSON.parse(body)) if body != ''
end
end
force_method = params['_method']
if force_method
method = force_method
params.delete('_method')
else
method = request.request_method
end
method.downcase!
@@routes[method].each do |item|
if request.path[1..-1].match(item[:regexp])
me = @@authenticate ? @@authenticate.call(params) : nil
case $~.length
when 1 then result = item[:fn].call(params, me)
when 2 then result = item[:fn].call($1, params, me)
when 3 then result = item[:fn].call($1, $2, params, me)
when 4 then result = item[:fn].call($1, $2, $3, params, me)
when 5 then result = item[:fn].call($1, $2, $3, $4, params, me)
else result = item[:fn].call($~, params, me)
end
return result.env if result.kind_of? MyResult
case method
when 'get', 'post'
if result.kind_of? String and ['{', '['].include? result.slice(0, 1)
json = result
else
json = result.to_json
end
return [200, {'Content-Type' => 'application/json', 'Content-Encoding' => 'gzip'}, gzip(json)]
else
return [200, {'Content-Type' => 'application/json', 'Content-Encoding' => 'gzip'}, gzip({:result => :success}.to_json)]
end
end
end
[404, {'Content-Type' => 'text/plain'}, 'Not found.']
rescue => e
result = {:message => e.message, :callstack => e.backtrace.join("\n")}
[500, {'Content-Type' => 'text/plain' }, e.message]
end
end
|