Home Blog CV Projects Patterns Notes Book Colophon Search

Apache and Lua with CJSON

9 Jul, 2020

On a previous version of this site, I had a static HTML that I wanted to be able to accept comments on.

The solution I chose was as follows:

First we'll need lua CJSON.

Just install it globally, mod_lua will pick it up:

sudo apt install -y lua-cjson

Now we'll enable mod_rewrite:

sudo a2enmod rewrite

Next add some rewrite config to the siteroot directory:

    <Directory /home/siteroot/>
      Options Indexes FollowSymLinks
      AllowOverride None
      Require all granted

      LogLevel alert rewrite:trace6

      RewriteEngine on
      RewriteCond %{REQUEST_METHOD}  =POST
      RewriteRule    ^blog/(.+?)/index\.html$  /blog/comment.lua?action=comment&post=$1
    </Directory>

Tip: Look in the Apache error or rewrite log with [rewrite prefixed lines to see any problems.

Here's the lua handler at blog/comment.lua:

local cjson = require "cjson"


function handle(r)
    local GET, GETMULTI = r:parseargs()
    local POST, POSTMULTI = r:parsebody(1024*1024)
    local json = cjson.encode({
        author = POST['author'] or "Anon",
        comment = POST['comment'] or ""
    })
    local file = io.open(string.format("/home/siteroot/blog/%s/_contrib/comment_%s.json", GET['post'], os.time()), "w")
    file:write(json)
    file:close(file)
    local handle = io.popen([[/usr/bin/python3 -u /home/apply2.py /home/siteroot -f -a]])
    local result = handle:read("*a")
    handle:close()
    local file = io.open(string.format("/home/siteroot/blog/%s/index.html", GET['post']), "r")
    result = file:read('*a')
    file:close(file)
    local html, i = string.gsub(result, "<h1>", '<p class="success">Comment added successfully</p><h1>')
    r:puts(html)
end

Comments

Be the first to comment.

Add Comment





Copyright James Gardner 1996-2020 All Rights Reserved. Admin.