Skip to content

Instantly share code, notes, and snippets.

@rafaelss
Created April 8, 2012 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelss/2334183 to your computer and use it in GitHub Desktop.
Save rafaelss/2334183 to your computer and use it in GitHub Desktop.
server {
listen 8081;
server_name localhost;
location /site {
internal;
postgres_escape $api_key $arg_api_key;
postgres_pass database;
postgres_query "SELECT id FROM sites WHERE api_key = $api_key";
postgres_rewrite no_rows 403;
postgres_output value;
}
location /exist {
internal;
postgres_escape $path $arg_path;
postgres_pass database;
postgres_query "SELECT id FROM templates WHERE site_id = $arg_site_id AND path = $path";
postgres_rewrite no_rows 404;
postgres_output value;
}
location /insert {
internal;
set_unescape_uri $body $arg_body;
postgres_escape $path $arg_path;
postgres_escape $body;
postgres_pass database;
postgres_query "INSERT INTO templates (site_id, path, body, created_at, updated_at) VALUES ($arg_site_id, $path, $body, NOW(), NOW()) RETURNING 'id'";
postgres_rewrite no_changes 422;
postgres_output none;
}
location /update {
internal;
set_unescape_uri $body $arg_body;
postgres_escape $body;
postgres_pass database;
postgres_query "UPDATE templates SET body = $body, updated_at = NOW() WHERE id = $arg_id";
postgres_rewrite no_changes 422;
postgres_output none;
}
location /delete {
internal;
postgres_pass database;
postgres_query "DELETE FROM templates WHERE id = $arg_id";
postgres_rewrite no_changes 404;
postgres_output none;
}
location / {
proxy_pass http://localhost:8082;
proxy_set_header X-Real-IP $remote_addr;
echo $request_body;
}
location ~ /(.+) {
lua_need_request_body on;
content_by_lua '
if ngx.var.arg_api_key then
res = ngx.location.capture("/site", { args = { api_key = ngx.var.arg_api_key } })
if res.status == ngx.HTTP_OK then
local site_id = res.body
local matches = ngx.re.match(ngx.var.echo_request_uri, "^\/([^\?]+)")
res2 = ngx.location.capture("/exist", { args = { site_id = site_id, path = matches[1] } })
local template_id = res2.body
if ngx.var.echo_request_method == "DELETE" then
if res2.status == ngx.HTTP_NOT_FOUND then
ngx.exit(res2.status)
else
res3 = ngx.location.capture("/delete", { args = { id = template_id } })
end
elseif ngx.var.echo_request_method == "PUT" then
if res2.status == ngx.HTTP_NOT_FOUND then
res3 = ngx.location.capture("/insert", { args = { site_id = site_id, path = matches[1], body = ngx.var.request_body } })
elseif res2.status == ngx.HTTP_OK then
res3 = ngx.location.capture("/update", { args = { id = template_id, body = ngx.var.request_body } })
else
ngx.exit(res2.status)
end
end
ngx.exit(res3.status)
else
ngx.exit(res.status)
end
else
ngx.exit(ngx.HTTP_FORBIDDEN)
end
';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment