Skip to content

Commit

Permalink
Serve files as bytes instead of text strings
Browse files Browse the repository at this point in the history
  • Loading branch information
dscottboggs committed Feb 15, 2020
1 parent 64e7fb4 commit bd2bc69
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
14 changes: 12 additions & 2 deletions src/cached_static_server.cr
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module CachedStaticServer

property parent_dir : Path
property port : UInt16
property cache = {} of Path => String
property cache = {} of Path => Bytes
property bind_address : String
property not_found_action : Proc(HTTP::Request, String) = ->default_not_found_action(HTTP::Request)

Expand All @@ -31,7 +31,17 @@ module CachedStaticServer
fullpath = dir / file
next read_files_into_cache fullpath if File.directory? fullpath
debug "caching file #{fullpath}"
cache[fullpath] = File.read fullpath
File.open fullpath do |file|
size = file.info.size
buf = Bytes.new LibC.malloc(size).as(Pointer(UInt8)), size
# uninitialized, forever-living (no GC) pointer.
# these need to be kept around for the life of the
# program anyway, and we're about to fill
# in the buffer, so why bother zeroing it?
read_count = file.read buf
raise "read #{read_count} bytes from file #{fullpath} of size #{size}" if read_count != size
cache[fullpath] = buf
end
end
end

Expand Down
8 changes: 7 additions & 1 deletion src/run.cr
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ server = HTTP::Server.new do |context|
begin
code, resp = config.serve context.request
context.response.status_code = code
resp.to_s context.response
if resp.is_a? String
resp.to_s context.response
elsif resp.is_a? Bytes
context.response.write resp
else
raise "received invalid response #{resp.inspect} with status #{code}"
end
rescue e
context.response.status = HTTP::Status::INTERNAL_SERVER_ERROR
context.response.puts e.message
Expand Down

0 comments on commit bd2bc69

Please sign in to comment.