Skip to content

Instantly share code, notes, and snippets.

@leafo
Last active February 12, 2016 04:59
Show Gist options
  • Save leafo/415d521e604d49dc3182 to your computer and use it in GitHub Desktop.
Save leafo/415d521e604d49dc3182 to your computer and use it in GitHub Desktop.
working ngx_postgres
user derek users;
worker_processes 1;
error_log logs/error.log;
# I like to use these two directives for development so I can have server and log in foreground
# daemon off;
# error_log stderr notice;
events {
worker_connections 1024;
}
http {
server {
listen 8080;
charset utf-8;
default_type application/json;
location / {
content_by_lua '
local query = require("query")
query("SELECT js FROM peeps.active_emailers()")
';
}
location ~ /person/(?<id>[0-9]+)$ {
content_by_lua '
local query = require("query")
query("SELECT js FROM peeps.get_person(?)", ngx.var.id)
';
}
location /search {
content_by_lua '
local query = require("query")
query("SELECT js FROM peeps.people_search(?)", ngx.var.arg_q)
';
}
}
}
local pgmoon = require("pgmoon")
local json = require("cjson") -- cjson comes with openresty
-- run the query, and write the output as json to the
return function(q, ...)
-- create a pointer to our database connection
local db = pgmoon.new({
host = "127.0.0.1",
port = "5432",
database = "d50b",
user = "d50b"
})
-- create a new connection, or pull from connection pool if available
db:connect()
-- quck script to interpolate query params if they are passed
if ... then
local varargs = {...}
local i = 0
q = q:gsub("%?", function()
i = i + 1
return db:escape_literal(varargs[i])
end)
end
-- run the query
-- assert will throw 500 error, and write to notice log if query fails. (this
-- is because a failed query returns two return values: nil, the error
-- message)
local res = assert(db:query(q))
-- write to the output to nginx
ngx.say(json.encode(res))
db:keepalive() -- give connection back to connection pool
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment