# hx/rack/application - Rack application to serve an Hx site dynamically # # Copyright (c) 2009-2010 MenTaLguY # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'cgi' require 'hx' require 'rack/mime' module Hx module Rack class Application def self.load_file(config_path) site = Hx::Site.load_file(config_path) new(site, site.options) end def initialize(input, options) @input = input @index_names = Array(options[:index_names] || ['index.html']) end def call(env) path = CGI.unescape(env['PATH_INFO']) path = '/' if path.empty? entry = nil has_trailing_slash = (path[-1..-1] == '/') # for non-slash-terminated paths, try the path directly unless has_trailing_slash begin effective_path = path[1..-1] entry = @input.get_entry(effective_path) rescue NoSuchEntryError end end # no entry? maybe it's a directory; look for an index entry unless entry path =~ %r(^/(.*?)/?$) prefix = $1 prefix = "#{prefix}/" unless prefix.empty? for index_name in @index_names begin effective_path = "#{prefix}#{index_name}" entry = @input.get_entry(effective_path) break rescue NoSuchEntryError end end # directory exists, but missing trailing slash? if entry and not has_trailing_slash return [301, {'Content-Type' => 'text/plain', 'Location' => "#{env['SCRIPT_NAME']}#{path}/"}, ["301 Moved Permanently"]] end end if entry content_type = entry['content_type'] unless content_type effective_path =~ /(\.[^.]+)$/ content_type = ::Rack::Mime.mime_type($1 || '') end content = entry['content'].to_s [200, {'Content-Type' => content_type}, [content]] else message = "#{env['SCRIPT_NAME']}#{path} not found" [404, {'Content-Type' => "text/plain"}, [message]] end end end end end