nginx+luaで画像返すやつ書いてみた。
nginxのLuaモジュール使ってみた。
OpenResty - a fast web app server by extending nginx
nginxにLuaモジュール組み込むのにコレ使った。
インストール方法
wget http://openresty.org/download/ngx_openresty-1.5.11.1.tar.gz cd ngx_openresty-1.5.11.1.tar.gz tar xvfz ngx_openresty-1.5.11.1.tar.gz cd ngx_openresty-1.5.11.1 ./configure --with-luajit gmake sudo gmake install
この辺でうまくいく。(EC2上だと)
Macだと普通にmakeコマンドとmake installコマンドでおk。
起動方法
/usr/local/openresty/nginx/sbin/nginx
再起動
/usr/local/openresty/nginx/sbin/nginx -s reload
停止
/usr/local/openresty/nginx/sbin/nginx -s stop
confファイル設定
emacs /usr/local/openresty/nginx/conf/nginx.conf
nginx.confの追加部分
server { listen 8081; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location ~ /(.*\.png) { set $image_path $1; content_by_lua_file /usr/local/openresty/lualib/send_image.lua; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
content_by_lua_fileでresponseを生成するコードを実行する
参照スライド
Using ngx_lua / lua-nginx-module in pixiv
/usr/local/openresty/lualib/send_image.lua
nginx.confで
set $image_path $1
って書いているのは、正規表現でlocalhost:8081/hoge.pngで$image_pathにhoge.pngが入るように。
そうすると
local image_path = ngx.var.image_path
でluaスクリプト内にnginxで読んだ値をluaスクリプト内で変数格納できたよー!って感じかな。
結構詰まってたのは
local file = io.open(source_fname,"r") ngx.say(file)
で画像返そうと思ったら、うまくいかなかった。
readオプションつけてるし、うまくいくと思ったらダメだった。
local file = io.open(source_fname) input_file_stream = file:read("*a") ngx.say(input_file_stream)
file:readを一回かましたら行けた。
さて、これのベンチマーク取りますかー。