您的位置:首页 > 理论基础 > 计算机网络

HTTP Server in 5 Lines With Webrick

2014-01-08 10:54 302 查看
Usually when I am prototyping a web UI - either in Javascript or Flex, I would just write a static html, because that's the simplest thing that works. But, once in a while, it doesn't work because of the security restrictions that the browser imposes on local
files. Maybe you want to use ajax calls(which is sometimes problematic on IE), trying to use the google maps api, or the FABridge, whatever the reason may be. Well, you can get around this problem easily using this ruby script:
require 'webrick'
server = WEBrick::HTTPServer.new :Port => 1234
server.mount "/", WEBrick::HTTPServlet::FileHandler, './'
trap('INT') { server.stop }
server.start


This runs a web server at http://localhost:1234/ which
mounts the top level directory to your current directory.

Update: Oops, it's not exactly that easy after all. In order to prevent caching - which you will want to do if you are doing development - you will want to write an extra class. The modified script:
require 'webrick'
class NonCachingFileHandler < WEBrick::HTTPServlet::FileHandler
def prevent_caching(res)
res['ETag']          = nil
res['Last-Modified'] = Time.now + 100**4
res['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
res['Pragma']        = 'no-cache'
res['Expires']       = Time.now - 100**4
end

def do_GET(req, res)
super
prevent_caching(res)
end

end

server = WEBrick::HTTPServer.new :Port => 1234
server.mount "/", NonCachingFileHandler , './'
trap('INT') { server.stop }
server.start


Not 5 lines anymore, bummer! The code for NonCachingFileHandler was stolen from unittest_js.

Add
, {:FancyIndexing => true} to the end of mount line,as Follows:

server.mount "/", NonCachingFileHandler , './', {:FancyIndexing => true}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐