How to do it...

We'll start with using one of the most basic functions in OpenResty and Lua, which is the content_by_lua_block block directive. This allows us to insert Lua code directly in line with our NGINX configuration, providing rapid and dynamic changes. The first recipe returns a basic string:

location /simpletest { 
    default_type 'text/plain'; 
    content_by_lua_block { 
        ngx.say('This is a simple test!') 
  } 
} 

If you browse to the URL (or use cURL to make the request), you should simply get This is a simple test as the HTTP response. Running a simple Apache Benchmark against this URL (just to show a baseline performance) shows that it can serve this URL over 20,000 times a second on a modestly resourced VM. While the code isn't overly complex, it does show that the overheads for adding Lua have a very minimal effect on performance.

If you need to return the data as JSON, then this is quite simple to do as well. Using the basic example, as we used previously, we can leverage the Lua CJSON library (compiled with OpenResty by default) to encode the output:

location /simplejsontest { 
        default_type 'application/json'; 
        content_by_lua_block { 
            local cjson = require "cjson.safe" 
            ngx.say(cjson.encode({test="Encoded with CJSON",enabled=true})) 
      } 
    } 

If we call the /simplejsontest URL, you should see the following output:

{"test":"Encoded with CJSON","enabled":true}
  

This, of course, barely scratches the surface of what can be achieved with Lua, but this should at least get you started.