page.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. mg.write("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n")
  2. mg.write([[
  3. <html><body>
  4. <p>This is another example of a Lua script, creating a web page served by the
  5. <a href="https://github.com/civetweb/civetweb/">CivetWeb web server</a>.
  6. </p><p>
  7. The following features are available:
  8. <ul>
  9. ]])
  10. mg.write("<li>" .. _VERSION .. " server pages</li>")
  11. if sqlite3 then
  12. mg.write("<li>sqlite3 binding</li>")
  13. end
  14. if lfs then
  15. mg.write("<li>lua file system</li>")
  16. end
  17. mg.write("</ul></p>\r\n")
  18. mg.write("<p> Today is " .. os.date("%A") .. "</p>\r\n")
  19. mg.write("<p> URI is " .. mg.request_info.uri .. "</p>\r\n")
  20. mg.write("<p>Database example:\r\n<pre>\r\n")
  21. -- Open database
  22. local db = sqlite3.open('requests.db')
  23. -- Note that the data base is located in the current working directory
  24. -- of the process if no other path is given here.
  25. -- Setup a trace callback, to show SQL statements we'll be executing.
  26. -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)
  27. -- Create a table if it is not created already
  28. db:exec([[
  29. CREATE TABLE IF NOT EXISTS requests (
  30. id INTEGER PRIMARY KEY AUTOINCREMENT,
  31. timestamp NOT NULL,
  32. method NOT NULL,
  33. uri NOT NULL,
  34. addr
  35. );
  36. ]])
  37. -- Add entry about this request
  38. local stmt = db:prepare(
  39. 'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
  40. stmt:bind_values(mg.request_info.request_method,
  41. mg.request_info.uri,
  42. mg.request_info.remote_port)
  43. stmt:step()
  44. stmt:finalize()
  45. -- Show all previous records
  46. mg.write('Previous requests:\n')
  47. stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
  48. while stmt:step() == sqlite3.ROW do
  49. local v = stmt:get_values()
  50. mg.write(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
  51. .. v[4] .. ' ' .. v[5] .. '\n')
  52. end
  53. -- Close database
  54. db:close()
  55. mg.write([[
  56. </pre>
  57. </p>
  58. </body></html>
  59. ]])