mirror of
https://gitea.invidious.io/iv-org/shard-kemal.git
synced 2024-08-15 00:53:36 +00:00
Refactor static file handler
This commit is contained in:
parent
21a3c6ad3c
commit
e4da65f1f2
4 changed files with 12 additions and 34 deletions
|
@ -17,7 +17,7 @@ at_exit do
|
||||||
config = Kemal.config
|
config = Kemal.config
|
||||||
logger = Kemal::Logger.new
|
logger = Kemal::Logger.new
|
||||||
config.add_handler logger
|
config.add_handler logger
|
||||||
config.add_handler Kemal::StaticHandler.new("./public")
|
config.add_handler Kemal::StaticFileHandler.new("./public")
|
||||||
config.add_handler Kemal::Handler::INSTANCE
|
config.add_handler Kemal::Handler::INSTANCE
|
||||||
|
|
||||||
server = HTTP::Server.new(config.port, config.handlers)
|
server = HTTP::Server.new(config.port, config.handlers)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
macro redirect(url)
|
macro redirect(url)
|
||||||
env.response.headers.add "Location", {{url}}
|
env.response.headers.add "Location", {{url}}
|
||||||
env.response.status_code = 301
|
env.response.status_code = 301
|
||||||
end
|
end
|
||||||
|
|
10
src/kemal/static_file_handler.cr
Normal file
10
src/kemal/static_file_handler.cr
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
require "http/server"
|
||||||
|
require "ecr/macros"
|
||||||
|
|
||||||
|
class Kemal::StaticFileHandler < HTTP::Handler
|
||||||
|
def call(request)
|
||||||
|
request_path = request.path.not_nil!
|
||||||
|
return call_next(request) if request_path == "/"
|
||||||
|
super
|
||||||
|
end
|
||||||
|
end
|
|
@ -1,32 +0,0 @@
|
||||||
require "http/server"
|
|
||||||
require "ecr/macros"
|
|
||||||
|
|
||||||
class Kemal::StaticHandler < HTTP::Handler
|
|
||||||
|
|
||||||
def initialize(@publicdir)
|
|
||||||
end
|
|
||||||
|
|
||||||
def call(request)
|
|
||||||
request_path = request.path.not_nil!
|
|
||||||
|
|
||||||
# Call next handler for processing
|
|
||||||
return call_next(request) unless request_path.starts_with? "/public"
|
|
||||||
file = request_path.split("/public/")[1] if request_path.starts_with?("/public")
|
|
||||||
file_path = File.expand_path("public/#{file}", Dir.working_directory)
|
|
||||||
if File.exists?(file_path)
|
|
||||||
HTTP::Response.new(200, File.read(file_path), HTTP::Headers{"Content-Type": mime_type(file_path)})
|
|
||||||
else
|
|
||||||
call_next(request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
private def mime_type(path)
|
|
||||||
case File.extname(path)
|
|
||||||
when ".txt" then "text/plain"
|
|
||||||
when ".htm", ".html" then "text/html"
|
|
||||||
when ".css" then "text/css"
|
|
||||||
when ".js" then "application/javascript"
|
|
||||||
else "application/octet-stream"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
Loading…
Reference in a new issue