Browse Source

use a Lua module and localize functions

bakins 12 years ago
parent
commit
72b25ea3c2
2 changed files with 27 additions and 17 deletions
  1. 25 16
      openresty/app.lua
  2. 2 1
      openresty/nginx.conf

+ 25 - 16
openresty/app.lua

@@ -1,7 +1,13 @@
+local _M = {}
+
 local cjson = require "cjson"
 local mysql = require "resty.mysql"
 local math = require "math"
 
+local encode = cjson.encode
+local random = math.random
+local insert = table.insert
+
 local mysqlconn = {
     host = "DBHOSTNAME",
     port = 3306,
@@ -10,21 +16,24 @@ local mysqlconn = {
     password = "benchmarkdbpass"
 }
 
-ngx.header.content_type = 'application/json'
-
-if ngx.var.uri == '/json' then
-    local resp = {message = "Hello, World!"}
-    ngx.print( cjson.encode(resp) )
-
-elseif ngx.var.uri == '/db' then
-    local db, err = mysql:new()
-    local ok, err = db:connect(mysqlconn)
-    local num_queries = tonumber(ngx.req.get_uri_args()["queries"]) or 1
-    local worlds = {}
-    for i=1, num_queries do
-        local wid = math.random(1, 10000)
-        table.insert(worlds, db:query('SELECT * FROM World WHERE id = '..wid)[1])
+function _M.handler(ngx)
+    ngx.header.content_type = 'application/json'
+    
+    if ngx.var.uri == '/json' then
+	local resp = {message = "Hello, World!"}
+	ngx.print( encode(resp) )
+    elseif ngx.var.uri == '/db' then
+	local db, err = mysql:new()
+	local ok, err = db:connect(mysqlconn)
+	local num_queries = tonumber(ngx.var.arg_queries) or 1
+	local worlds = {}
+	for i=1, num_queries do
+	    local wid = random(1, 10000)
+	    insert(worlds, db:query('SELECT * FROM World WHERE id = '..wid)[1])
+	end
+	ngx.print( encode(worlds) )
+	local ok, err = db:set_keepalive(0, 256)
     end
-    ngx.print( cjson.encode(worlds) )
-    local ok, err = db:set_keepalive(0, 256)
 end
+
+return _M

+ 2 - 1
openresty/nginx.conf

@@ -8,10 +8,11 @@ events {
 
 http {
     access_log off;
+    lua_package_path 'CWD/openresty/?.lua;;';	
     server {
         listen       8080;
         location / {
-            content_by_lua_file 'CWD/openresty/app.lua';
+            content_by_lua 'require("app").handler(ngx)';
         }
     }
 }