LoginSignup
14
16

More than 5 years have passed since last update.

ngx_luaのコードをCLIで実行できるresty-cliが超便利な件

Posted at

nginxを拡張する上でとても便利なngx_luaですが、nginx上でコードが実行される性質上、非常に簡単なコードを実行する場合でもcurl等でHTTPリクエストを送る手順が必要でngx_luaによるアプリケーションを開発・デバッグする際に面倒だと感じることがよくありました。

resty-cliの登場

しかし、昨年末にresty-cliというモジュールがOpenRestyに加わりました。これを使うとngx_luaのコードをCLIで実行できます。

resty-cliをインストールする

resty-cliは最新のOpenRestyに含まれているので、利用するにはOpenRestyごとインストールすると楽です。

$ wget http://openresty.org/download/ngx_openresty-1.7.7.1.tar.gz
$ tar ngx_openresty-1.7.7.1.tar.gz
$ cd ngx_openresty-1.7.7.1
$ ./configure
$ make
$ sudo make

resty-cliでngx_luaのコードを実行する

resty-cliの実態はrestyという名前の単一のPerlスクリプトです。こんな感じでインラインコードを実行できます。

$ /usr/local/openresty/bin/resty -e 'ngx.say("nginx")'
nginx
$ /usr/local/openresty/bin/resty -e 'print(ngx.now())'
1422835556.82
$

CLIですが、ngx_luaのコードが実行できました。上記のは非常に簡単な例ですが、lua-resty-mysqllua-resty-redisのようにngx_luaのAPIをバリバリ使っているモジュールのコードも実行できます。

一方で多少制限もあってすべてのAPIがresty-cliで実行できるわけではありません。例えばnginxの内部変数を参照しようとするとエラーになります。

$ /usr/local/openresty/bin/resty -e 'ngx.say(ngx.var.nginx_version)'
(command line -e):1: API disabled in the current context
$

とはいえその他のresty系モジュールも普通に実行できるのでngx_luaを使って開発しているエンジニアならresty-cliを使わない理由はないと言ってよいでしょう。

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16