Created
January 27, 2014 13:01
-
-
Save localhots/b3d0520f612f534eca89 to your computer and use it in GitHub Desktop.
Tiny static serving server written in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%w[ logger yaml rack eventmachine ].each(&method(:require)) | |
log = Logger.new(STDOUT) | |
config = YAML.load_file('config.yml') | |
Thread.new{ EM.run } | |
templates = config['storage']['templates'].map{ |tpl| config['storage']['root'] + tpl } | |
cache = templates.map{ |tpl| Dir[tpl] }.inject(:+).keep_if{ |f| File.file?(f) } | |
cache = Hash[cache.map do |f| | |
l = config['storage']['root'].length | |
[f.slice(l, f.length - l), File.binread(f)] | |
end] | |
run ->(env){ | |
file = env['REQUEST_PATH'] | |
return [404, {}, ['404 Not Found']] unless cache.keys.include?(file) | |
headers = {} | |
ext = '.' << file.split(?.).last | |
headers['Content-Type'] = Rack::Mime::MIME_TYPES[ext] || 'text/plain' | |
headers['Content-Length'] = cache[file].length.to_s | |
EM.defer do | |
log.info 'Performing an async call to ' << config['callback']['url'] % file | |
end | |
[200, headers, [cache[file]]] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
storage: | |
root: '/usr/share/web/public' | |
templates: | |
- '/**/*' | |
callback: | |
url: 'http://count.example.com/?path=%s' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment