page.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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="http://code.google.com/p/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. -- Setup a trace callback, to show SQL statements we'll be executing.
  24. -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)
  25. -- Create a table if it is not created already
  26. db:exec([[
  27. CREATE TABLE IF NOT EXISTS requests (
  28. id INTEGER PRIMARY KEY AUTOINCREMENT,
  29. timestamp NOT NULL,
  30. method NOT NULL,
  31. uri NOT NULL,
  32. addr
  33. );
  34. ]])
  35. -- Add entry about this request
  36. local stmt = db:prepare(
  37. 'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
  38. stmt:bind_values(mg.request_info.request_method,
  39. mg.request_info.uri,
  40. mg.request_info.remote_port)
  41. stmt:step()
  42. stmt:finalize()
  43. -- Show all previous records
  44. mg.write('Previous requests:\n')
  45. stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
  46. while stmt:step() == sqlite3.ROW do
  47. local v = stmt:get_values()
  48. mg.write(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
  49. .. v[4] .. ' ' .. v[5] .. '\n')
  50. end
  51. -- Close database
  52. db:close()
  53. mg.write([[
  54. </pre>
  55. </p>
  56. </body></html>
  57. ]])