aboutsummaryrefslogtreecommitdiff
path: root/server.lua
blob: 3625423f27da79ac19135d5645441c633238dec8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
local root_path = "/home/gemini"

local function handle_gemini()
    local sock = ngx.req.socket(true)
    if not sock then return end
    
    sock:settimeout(5000)
    local line, err = sock:receive("*l")
    if not line then return end

    -- Декодируем %20 (пробелы) из URL, прилетевшего от Amfora
    local url = line:match("gemini://[^/]+(.*)")
    if not url or url == "" or url == "/" then
        url = "/index.gmi"
    end
    local path = url:gsub("%%20", " ")

    local local_path = root_path .. path
    local file = io.open(local_path, "rb") -- Бинарное чтение rb
    
    if not file then
        sock:send("51 Resource not found\r\n")
        return
    end

    local content = file:read("*all")
    file:close()

    -- Выставляем правильный MIME-тип по расширению
    local mime = "text/plain; charset=utf-8" -- Дефолт для неизвестных файлов/логов
    
    if path:match("%.gmi$") or path:match("%.gemini$") then
        mime = "text/gemini; charset=utf-8"
    elseif path:match("%.md$") or path:match("%.markdown$") then
        mime = "text/markdown; charset=utf-8"
    elseif path:match("%.jpg$") or path:match("%.jpeg$") then
        mime = "image/jpeg"
    elseif path:match("%.png$") then
        mime = "image/png"
    elseif path:match("%.pdf$") then
        mime = "application/pdf"
    end

    sock:send("20 " .. mime .. "\r\n")
    sock:send(content)
end

handle_gemini()