1require "json"
2-- json library needs to be available
3
4
5local http_status = "200 OK";
6local response_table = {};
7
8
9if mg.request_info.request_method == "GET" then
10
11  response_table["result"] = "ok";
12  response_table["data"] = {};
13  for i=1,10 do
14    response_table.data[i] = {name = "sensor" .. i, value = 20+i};
15  end
16
17elseif mg.request_info.request_method == "PUT" then
18
19  local request_len = mg.request_info.content_length
20  local read_len = 0
21  local request_body_sep = {}
22  local error_reading = false
23
24  repeat
25    local chunk = mg.read()
26	if chunk then
27	   read_len = read_len + #chunk
28	   request_body_sep[#request_body_sep+1] = chunk
29	else
30	   error_reading = true;
31	end
32  until ((read_len == request_len) or error_reading);
33
34
35  if (error_reading) then
36    response_table["error"] = "ok";
37    response_table["status"] = "error reading request body data";
38  else
39    local request_body = table.concat(request_body_sep)
40    local isok, request_table = pcall(json.parse, request_body)
41
42    -- TODO: check "isok", then check all arguments in "request_table",
43
44    response_table["result"] = "ok";
45    response_table["data"] = {name = request_table};
46  end
47
48else
49
50  http_status = "403 Forbidden";
51  response_table["result"] = "error";
52  response_table["status"] = "invalid method " .. mg.request_info.request_method;
53
54end
55
56
57local response_body = json.stringify(response_table)
58mg.write("HTTP/1.1 " .. http_status .. "\r\n")
59mg.write("Content-Type: application/json; charset=UTF-8\r\n")
60mg.write("Content-Length: ".. #response_body .."\r\n")
61mg.write("\r\n")
62mg.write(response_body)
63