Class: Mayu::Server::FileServer
- Inherits:
-
Object
- Object
- Mayu::Server::FileServer
- Extended by:
- T::Sig
- Defined in:
- lib/mayu/server/file_server.rb
Defined Under Namespace
Classes: FoundFile
Constant Summary collapse
- DEFAULT_MEMORY_CACHE_MAX_SIZE =
TODO: Make configurable. A higher value means less filsystem IO, but obviously consumes more memory.
T.let(1024, Integer)
- CACHE_MAX_AGE =
T.let(60 * 60 * 24 * 7, Integer)
- CACHE_CONTROL =
T.let( { "cache-control" => "public, max-age=#{CACHE_MAX_AGE}, immutable" }.freeze, T::Hash[String, String] )
- BROTLI_CONTENT_ENCODING =
T.let({ "content-encoding" => "br" }.freeze, T::Hash[String, String])
Instance Method Summary collapse
-
#initialize(root_dir, memory_cache_max_size: DEFAULT_MEMORY_CACHE_MAX_SIZE) ⇒ FileServer
constructor
A new instance of FileServer.
- #serve(filename, accept_encodings: []) ⇒ Object
Constructor Details
#initialize(root_dir, memory_cache_max_size: DEFAULT_MEMORY_CACHE_MAX_SIZE) ⇒ FileServer
Returns a new instance of FileServer.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/mayu/server/file_server.rb', line 34 def initialize( root_dir, memory_cache_max_size: DEFAULT_MEMORY_CACHE_MAX_SIZE ) @root_dir = root_dir @found_files = T.let( T::Hash[String, FoundFile].new do |h, filename| if found_file = find_file(filename) h[filename] = found_file end end, T::Hash[String, FoundFile] ) @memory_cache_max_size = memory_cache_max_size @memory_cache = T.let({}, T::Hash[String, String]) end |
Instance Method Details
#serve(filename, accept_encodings: []) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/mayu/server/file_server.rb', line 57 def serve(filename, accept_encodings: []) found_file = @found_files[filename] unless found_file raise Errors::FileNotFound, "Could not find file #{filename}" end headers = { **CACHE_CONTROL, "content-type" => add_charset(found_file.content_type) } if accept_encodings.include?("br") if brotlied = @found_files["#{filename}.br"] return( Protocol::HTTP::Response[ 200, { **headers, **BROTLI_CONTENT_ENCODING }, read_file(brotlied) ] ) end end contents = read_file(found_file) Protocol::HTTP::Response[200, headers, read_file(found_file)] end |