|
| 1 | +-- function to split the uri, |
| 2 | +-- sep defines the delimiter |
| 3 | +function splitstr(inputstr, sep) |
| 4 | + if sep == nil then |
| 5 | + sep = "%s" |
| 6 | + end |
| 7 | + local t={} ; i=1 |
| 8 | + for str in string.gmatch(inputstr, "([^"..sep.."]+)") do |
| 9 | + t[i] = str |
| 10 | + i = i + 1 |
| 11 | + end |
| 12 | + return t |
| 13 | +end |
| 14 | + |
| 15 | +local mysql = require "resty.mysql" |
| 16 | +local db, err = mysql:new() |
| 17 | +if not db then |
| 18 | + ngx.say("failed to instantiate mysql: ", err) |
| 19 | + return |
| 20 | +end |
| 21 | + |
| 22 | +db:set_timeout(1000) -- 1 sec |
| 23 | + |
| 24 | +local ok, err, errcode, sqlstate = db:connect{ |
| 25 | + host = "127.0.0.1", |
| 26 | + port = 3306, |
| 27 | + database = "files", |
| 28 | + user = "magix", |
| 29 | + password = "magix", |
| 30 | + charset = "utf8", |
| 31 | + max_packet_size = 1024 * 1024, |
| 32 | +} |
| 33 | + |
| 34 | +if not ok then |
| 35 | + ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate) |
| 36 | + return |
| 37 | +end |
| 38 | + |
| 39 | +local urlsplit = splitstr(ngx.var.uri, '/') |
| 40 | + |
| 41 | +-- le generic mysql query doing secret stuff. |
| 42 | +res, err, errcode, sqlstate = db:query("update files set downloads=downloads+1 where name='"..urlsplit[3].."'") |
| 43 | +if not res then |
| 44 | + ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".") |
| 45 | + return |
| 46 | +end |
| 47 | + |
| 48 | + |
| 49 | +-- put it into the connection pool of size 100, |
| 50 | +-- with 10 seconds max idle timeout |
| 51 | +local ok, err = db:set_keepalive(10000, 100) |
| 52 | +if not ok then |
| 53 | + ngx.say("failed to set keepalive: ", err) |
| 54 | + return |
| 55 | +end |
| 56 | + |
0 commit comments