Skip to content

Commit

Permalink
feat(ssl): add method sendfile
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Dec 17, 2023
1 parent d0820d9 commit 8d95b6c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 44 deletions.
45 changes: 1 addition & 44 deletions http/server.lua
Original file line number Diff line number Diff line change
Expand Up @@ -322,45 +322,6 @@ function methods:send(...)
return true
end

-- used for ssl
local function sendfile(sock, path, count, offset)
local f, err = io.open(path)
if not f then
return nil, err
end

if offset then
f:seek('set', offset)
end

local chunk = 4096
local sent = 0
local data

while count > 0 do
data, err = f:read(chunk > count and count or chunk)
if not data then
break
end

_, err = sock:send(data)
if err then
break
end

sent = sent + #data
count = count - #data
end

f:close()

if err then
return nil, err
end

return sent
end

local function http_send_file(self, path, size, count, offset)
local resp = self.resp
local sock = self.sock
Expand Down Expand Up @@ -391,11 +352,7 @@ local function http_send_file(self, path, size, count, offset)

local ret

if sock.sendfile then
ret, err = sock:sendfile(path, count, offset)
else
ret, err = sendfile(sock, path, count, offset)
end
ret, err = sock:sendfile(path, count, offset)
if not ret then
return nil, err
end
Expand Down
41 changes: 41 additions & 0 deletions ssl.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
local socket = require 'eco.socket'
local ssl = require 'eco.core.ssl'
local bufio = require 'eco.bufio'
local file = require 'eco.file'

local M = {}

Expand Down Expand Up @@ -41,6 +42,46 @@ function cli_methods:write(data)
return self:send(data)
end

function cli_methods:sendfile(path, len, offset)
local fd, err = file.open(path)
if not fd then
return nil, err
end

if offset then
file.lseek(fd, offset, file.SEEK_SET)
end

local b = bufio.new(fd)

local chunk = 4096
local sent = 0
local data

while len > 0 do
data, err = b:read(chunk > len and len or chunk)
if not data then
break
end

_, err = self:send(data)
if err then
break
end

sent = sent + #data
len = len - #data
end

file.close(fd)

if not err or err == 'eof' then
return sent
end

return nil, err
end

--[[
Reads according to the given pattern, which specify what to read.
Expand Down

0 comments on commit 8d95b6c

Please sign in to comment.