Write your own Lua module for openresty applications

Time:2021-4-23

https://www.bilibili.com/vide…

Today, I will demonstrate how to write my own Lua module in openresty application step by step.

Write your own Lua module for openresty applications

Let’s put our simple openresty application in a new directory namedtest-module

cd ~/
mkdir test-module/
cd test-module/

Write your own Lua module for openresty applications

Then we create the subdirectory structure as usual.

mkdir logs conf lua

Write your own Lua module for openresty applications

Note that unlike the “Hello world” example in the previous tutorial, we created one herelua/Directory to store our Lua module files.

Now, let’s start atluaCreate our own Lua module file, namedhello.lua

vim lua/hello.lua

We edit as follows:

  1. Declare Lua module table_M
  2. Then add a new module namedgreetFunction of.
  3. Finally, don’t forget to return to the module table at the end.
local _M = {}

function _M.greet(name)
    ngx.say("Greetings from ", name)
end

return _M

It’s done! A very simple Lua module is completed.

Now it’s time to createnginx.confIt’s time to configure the file.

vim conf/nginx.conf

We quickly complete the following editing operations:

  1. We quickly write out the relatively fixed configuration.
  2. stayhttp {}In the configuration block, we should tell openresty where our Lua module is.
  3. Note that special variables$prefixIt is used by nginx at run time-pOption value.
  4. Then we create an HTTP server to listen to port 8080.
  5. And configure it at the rootcontent_by_lua"_block
  6. We use it hererequireLoading Lua module with built-in functionhello
  7. We call it with one parametergreetFunction.
worker_processes 1;

events {
    worker_connections 1024;
}

http {
    lua_package_path "$prefix/lua/?.lua;;";

    server {
        listen 8080 reuseport;

        location / {
            default_type text/plain;
            content_by_lua_block {
                local hello = require "hello"
                hello.greet("a Lua module")
            }
        }
    }
}

Let’s check the whole tree now.

tree .

It seems all right.

Now start the openresty application.

nginx -p $PWD/

Write your own Lua module for openresty applications


It’s time to use itcurlThe command line tool queries our HTTP interface.

curl 'http://127.0.0.1:8080/'

Write your own Lua module for openresty applications

Cool, our Lua module is working.

We can also test it in a web browser.

Write your own Lua module for openresty applications

If you see the 500 error page, there must be an error in your Lua code.

In this case, you should checklogsUnder subdirectoryerror.logDocuments.

tail logs/error.log

Write your own Lua module for openresty applications

We don’t have any error messages here, as expected.

It is worth noting that our Lua module was loaded in the first request, and subsequent requests only use the Lua module cached in memory.
To avoid the overhead of the first request, we can preload the Lua module when the server starts.

To do that, we need to edit itnginx.confDocuments.

vim conf/nginx.conf

stayhttp {}Block, we add oneinit_by_lua_blockInstructions. In that context, we load our Lua module.

    http {
        init_by_lua_block {
            require "hello"
        }
        ...

Write your own Lua module for openresty applications

init_by_lua_blockIt runs when the openresty server starts.

Test the configuration.

nginx -p $PWD/ -t

Write your own Lua module for openresty applications

no problem.

Now we send theHUPSignal to reload the server.
Now we reload the server by sending the HUP signal to the nginx master process.

kill -HUP `cat logs/nginx.pid`

Write your own Lua module for openresty applications

The process ID of the main process is stored in this filenginx.pidFile.

Send the HTTP request again.

curl 'http://127.0.0.1:8080/'

Write your own Lua module for openresty applications

The same behavior, only a little faster this time.
If you like this tutorial, please subscribe to this blog and ourYouTube channelorStation B channel. thank you!

About this article and Related videos

This article and the associated videos are all created by our openresty demo system from a very simpleScript file Automatically generated.

About the author

Zhang Yichun is an open source projectOpenResty®The founder of theOpenResty Inc.The founder and CEO of the company. He contributed a lot of third-party modules of nginx, quite a lot of nginx andLuaJITCore patch, and designedOpenResty XRayAnd other products.

Focus on us

If you like this article, please follow usOpenResty Inc.Company’sBlog website. Also welcome to scan code to pay attention to our WeChat official account:

Write your own Lua module for openresty applications

translate

We provideEnglish versionThe original text and Chinese Version (this article). We also welcome readers to provide translation versions in other languages. As long as the full text translation does not include ellipsis, we will consider it. Thank you very much!

Recommended Today

Envoy announced alpha version of native support for windows

Author: sunjay Bhatia Since 2016, porting envoy to the windows platform has been an important part of the projectOne of the goalsToday, we are excited to announce the alpha version of envoy’s windows native support. The contributor community has been working hard to bring the rich features of envoy to windows, which is another step […]