summaryrefslogtreecommitdiff
path: root/server/src/proto.lua
blob: 78d347a109b77e629105f902483bc227279f2cb9 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
local thread   = require 'bee.thread'
local json     = require 'json'
local response = thread.channel 'response'

local log = setmetatable({}, {__index = function (self, level)
    self[level] = function (...)
        local t = table.pack(...)
        for i = 1, t.n do
            t[i] = tostring(t[i])
        end
        local buf = table.concat(t, '\t')
        response:push('log', {
            level = level,
            buf   = buf,
        })
    end
    return self[level]
end})

local function readProtoHeader()
    local header = io.read 'l'
    if header:sub(1, #'Content-Length') == 'Content-Length' then
        return header
    elseif header:sub(1, #'Content-Type') == 'Content-Type' then
        return nil
    else
        log.error('Proto header error:', header)
        return nil
    end
end

local function readProtoContent(header)
    local len = tonumber(header:match('%d+'))
    if not len then
        log.error('Proto header error:', header)
        return nil
    end
    local buf = io.read(len+2)
    if not buf then
        return nil
    end
    local suc, res = pcall(json.decode, buf)
    if not suc then
        log.error('Proto error:', buf)
        return nil
    end
    return res
end

local function readProto()
    local header = readProtoHeader()
    if not header then
        return
    end
    local data = readProtoContent(header)
    if not data then
        return
    end
    response:push('proto', data)
end

while true do
    readProto()
end