page.lp 1.54 KB
Newer Older
1 2 3 4
HTTP/1.0 200 OK
Content-Type: text/html

<html><body>
5

Sergey Lyubka's avatar
Sergey Lyubka committed
6

7 8 9 10 11
<p>This is an example Lua server page served by
<a href="http://code.google.com/p/mongoose">Mongoose web server</a>.
Mongoose has Lua, Sqlite, and other functionality built in the binary.
This example page stores the request in the Sqlite database, and shows
all requests done previously.</p>
12
<p> Today is <? mg.write(os.date("%A")) ?>
13

14 15
<pre>
<?
16 17
  -- for k,v in pairs(_G) do mg.write(k, '\n') end

18 19
  -- Open database
  local db = sqlite3.open('requests.db')
Sergey Lyubka's avatar
Sergey Lyubka committed
20

21
  -- Setup a trace callback, to show SQL statements we'll be executing.
22
  -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)
Sergey Lyubka's avatar
Sergey Lyubka committed
23

24 25 26 27 28 29 30
  -- Create a table if it is not created already
  db:exec([[
    CREATE TABLE IF NOT EXISTS requests (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp NOT NULL,
      method NOT NULL,
      uri NOT NULL,
31
      addr
32 33
    );
  ]])
Sergey Lyubka's avatar
Sergey Lyubka committed
34

35

36 37 38
  -- Add entry about this request
  local stmt = db:prepare(
    'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
39 40 41
  stmt:bind_values(mg.request_info.request_method,
                   mg.request_info.uri,
                   mg.request_info.remote_port)
42 43
  stmt:step()
  stmt:finalize()
Sergey Lyubka's avatar
Sergey Lyubka committed
44

45
  -- Show all previous records
46
  mg.write('Previous requests:\n')
47 48 49
  stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
  while stmt:step() == sqlite3.ROW do
    local v = stmt:get_values()
50
    mg.write(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
51 52
          .. v[4] .. ' ' .. v[5] .. '\n')
  end
Sergey Lyubka's avatar
Sergey Lyubka committed
53

54 55 56 57
  -- Close database
  db:close()
?>
</pre></body></html>