websocket.lua 1.3 KB

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