Return JSON responses when using OpenResty + Lua

I've written few related post that may be interesting have a look to first:


There are different ways we could achieve this purpose and it will depends on your needs:

 1 way

In our case and because we are working building an API we want to force all responses as application/json MINE encode type + to a specific charset utf-8 so to achieve that we have to modify our ngnix.conf file, like so:

server {  
    ...
    charset utf-8;
    charset_types application/json;
    default_type application/json;
...

Note: this bit doesn't have anything to do with Lua

Note: a charset will be applied to a application/json MINE just if we add a specific directive to allow that behaviour charset_types application/json;

This way our responses from Lua will looks like:

ngx.status = ngx.HTTP_OK  
ngx.say(cjson.encode({ status = true }))  
return ngx.exit(ngx.HTTP_OK)  
2 way

From our Lua code we could do the following to return a JSON response:

ngx.status = ngx.HTTP_OK  
ngx.header.content_type = "application/json; charset=utf-8"  
ngx.say(cjson.encode({ status = true }))  
return ngx.exit(ngx.HTTP_OK)  

Optionally we could disable the default_type to be used by Lua in our nginx.conf file, like so:

server {  
    ...
    lua_use_default_type off;
...

Note: this will just ensure we are disabling a default_type to be returned on each response so will be foreced to set one before returning the response if we wish to have a Content-Type set


Either way the server response will looks like:


Resources