websocket.lua 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. -- Open database
  2. local db = sqlite3.open('requests.db')
  3. if db then
  4. db:busy_timeout(200);
  5. -- Create a table if it is not created already
  6. db:exec([[
  7. CREATE TABLE IF NOT EXISTS requests (
  8. id INTEGER PRIMARY KEY AUTOINCREMENT,
  9. timestamp NOT NULL,
  10. method NOT NULL,
  11. uri NOT NULL,
  12. addr
  13. );
  14. ]])
  15. end
  16. local function logDB(method)
  17. -- Add entry about this request
  18. local r;
  19. --repeat
  20. r = db:exec([[INSERT INTO requests VALUES(NULL, datetime("now"), "]] .. method .. [[", "]] .. mg.request_info.uri .. [[", "]] .. mg.request_info.remote_port .. [[");]]);
  21. --until r~=5;
  22. ---[[
  23. -- alternative logging (to a file)
  24. local f = io.open("R:\\log.txt", "a");
  25. f:write(os.date() .. " - " .. method .. " - " .. mg.request_info.uri .. " - " .. mg.request_info.remote_port .. " <" .. r .. ">\n")
  26. f:close()
  27. --]]
  28. end
  29. -- Callback for "Websocket ready"
  30. function ready()
  31. logDB("WEBSOCKET READY")
  32. end
  33. -- Callback for "Websocket received data"
  34. function data(bits, content)
  35. logDB(string.format("WEBSOCKET DATA (%x)", bits))
  36. return true;
  37. end
  38. -- Callback for "Websocket is closing"
  39. function close()
  40. logDB("WEBSOCKET CLOSE")
  41. -- Close database
  42. db:close()
  43. end
  44. logDB("WEBSOCKET PREPARE")
  45. return true; -- could return false to reject the connection before the websocket handshake