page.lp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?
  2. -- Lua server pages have full control over the output, including HTTP
  3. -- headers they send to the client. Send HTTP headers:
  4. print('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n')
  5. ?><html><body>
  6. <p>This is an example Lua server page served by
  7. <a href="http://code.google.com/p/mongoose">Mongoose web server</a>.
  8. Mongoose has Lua, Sqlite, and other functionality built in the binary.
  9. This example page stores the request in the Sqlite database, and shows
  10. all requests done previously.</p>
  11. <pre>
  12. <?
  13. -- Open database
  14. local db = sqlite3.open('requests.db')
  15. -- Setup a trace callback, to show SQL statements we'll be executing.
  16. -- db:trace(function(data, sql) print('Executing: ' .. sql .. '\n') end, nil)
  17. -- Create a table if it is not created already
  18. db:exec([[
  19. CREATE TABLE IF NOT EXISTS requests (
  20. id INTEGER PRIMARY KEY AUTOINCREMENT,
  21. timestamp NOT NULL,
  22. method NOT NULL,
  23. uri NOT NULL,
  24. user_agent
  25. );
  26. ]])
  27. -- Add entry about this request
  28. local stmt = db:prepare(
  29. 'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
  30. stmt:bind_values(request_info.request_method, request_info.uri,
  31. request_info.http_headers['User-Agent'])
  32. stmt:step()
  33. stmt:finalize()
  34. -- Show all previous records
  35. print('Previous requests:\n')
  36. stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
  37. while stmt:step() == sqlite3.ROW do
  38. local v = stmt:get_values()
  39. print(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
  40. .. v[4] .. ' ' .. v[5] .. '\n')
  41. end
  42. -- Close database
  43. db:close()
  44. ?>
  45. </pre></body></html>