diff --git a/src/grip/application.cr b/src/grip/application.cr index 3551f46..4944b25 100644 --- a/src/grip/application.cr +++ b/src/grip/application.cr @@ -11,7 +11,7 @@ module Grip getter exception_handler : Grip::Handlers::Exception getter pipeline_handler : Grip::Handlers::Pipeline getter websocket_handler : Grip::Routers::WebSocket - getter static_handler : Grip::Handlers::Static? + getter static_handler : Array(Grip::Handlers::Static) = [] of Grip::Handlers::Static property router : Array(HTTP::Handler) @@ -26,8 +26,8 @@ module Grip @pipeline_handler = Grip::Handlers::Pipeline.new(@http_handler, @websocket_handler) @exception_handler = Grip::Handlers::Exception.new(@environment) - if serve_static - @static_handler = Grip::Handlers::Static.new(pubilc_dir, fallthrough, directory_listing) + serve_static && static_routes.each do |route, path| + @static_handler << Grip::Handlers::Static.new(path, fallthrough, directory_listing, route) end @router = [ @@ -54,6 +54,10 @@ module Grip "./public" end + def static_routes : Hash(String, String) + {"/" => pubilc_dir} + end + def fallthrough : Bool false end @@ -63,8 +67,8 @@ module Grip end def server : HTTP::Server - if serve_static - @router.insert(1, @static_handler.not_nil!) + serve_static && @static_handler.each do |handler| + @router.insert(1, handler) end HTTP::Server.new(@router) diff --git a/src/grip/handlers/static.cr b/src/grip/handlers/static.cr index ee1f56c..6cc5277 100644 --- a/src/grip/handlers/static.cr +++ b/src/grip/handlers/static.cr @@ -8,8 +8,8 @@ module Grip module Handlers class Static < HTTP::StaticFileHandler - def initialize(public_dir : String, fallthrough = false, directory_listing = false) - super + def initialize(public_dir : String, @fallthrough = false, @directory_listing = false, @routing = "/") + @public_dir = Path.new(public_dir).expand end def call(context : HTTP::Server::Context) @@ -28,9 +28,14 @@ module Grip is_dir_path = dir_path? original_path expanded_path = Path.posix(request_path).expand("/").to_s expanded_path += "/" if is_dir_path && !dir_path?(expanded_path) + relative_path = request_path.lchop?(routing) || begin + call_next(context) + expanded_path + end + is_dir_path = dir_path? expanded_path - file_path = File.join(@public_dir, expanded_path) - root_file = File.join(@public_dir, expanded_path, "index.html") + file_path = File.join(@public_dir, Path[relative_path]) + root_file = File.join(@public_dir, Path[relative_path], "index.html") if is_dir_path && File.exists? root_file return if etag(context, root_file) @@ -103,6 +108,8 @@ module Grip def self.config_gzip?(config) config.is_a?(Hash) && config["gzip"] == true end + + getter routing : String end end end