- when building for release, embed the static files in binary

This commit is contained in:
Alex Ling 2020-02-15 23:29:11 +00:00
parent 0c177c3d31
commit 21fcde944d
6 changed files with 47 additions and 11 deletions

BIN
mango

Binary file not shown.

View File

@ -15,7 +15,7 @@ license: MIT
dependencies:
kemal:
github: kemalcr/kemal
kemal-basic-auth:
github: kemalcr/kemal-basic-auth
sqlite3:
github: crystal-lang/crystal-sqlite3
baked_file_system:
github: schovi/baked_file_system

View File

@ -1,14 +1,6 @@
require "kemal"
require "./storage"
def request_path_startswith(env, ary)
ary.each do |prefix|
if env.request.path.starts_with? prefix
return true
end
end
return false
end
require "./util"
class AuthHandler < Kemal::Handler
exclude ["/login"]

View File

@ -3,6 +3,7 @@ require "./config"
require "./library"
require "./storage"
require "./auth_handler"
require "./static"
require "./util"
class Server
@ -276,6 +277,11 @@ class Server
end
add_handler AuthHandler.new @storage
{% if flag?(:release) %}
# when building for relase, embed the static files in binary
serve_static false
add_handler StaticHandler.new
{% end %}
end
def start

29
src/static.cr Normal file
View File

@ -0,0 +1,29 @@
require "baked_file_system"
require "kemal"
require "gzip"
require "./util"
class FS
extend BakedFileSystem
bake_folder "../public"
end
class StaticHandler < Kemal::Handler
property dirs : Array(String)
def initialize
@dirs = ["/css", "/js"]
end
def call(env)
if request_path_startswith env, @dirs
file = FS.get? env.request.path
return call_next env if file.nil?
slice = Bytes.new file.size
file.read slice
return send_file env, slice, file.mime_type
end
call_next env
end
end

View File

@ -23,3 +23,12 @@ end
def hash_to_query(hash)
hash.map { |k, v| "#{k}=#{v}" }.join("&")
end
def request_path_startswith(env, ary)
ary.each do |prefix|
if env.request.path.starts_with? prefix
return true
end
end
return false
end