proper way to check for request method in nginx_lua

lua, nginx

Solution

Lua's method constants, such as `ngx.HTTP_GET`, are according to their documentation, mainly for `ngx.location*` calls.

So there is no "better" way of checking your method in Lua than comparing it with `GET` and the rest of the method strings.

However I would seriously consider using the "evil" `if` to split your requests based on method on nginx level.

This gives you the benefit of allowing you to configure separate logging, error handling etc. per method.

Problem

I am trying to write a REST interface using nginx and lua. What I'd like to know is, what is the best way to check for the request method? If it's a GET, I need to query a db. If it's a POST or DELETE, I need to run another lua script to update the database. So far, this is what my code looks like to test what the request method is: ``` #curl -i -X GET 'http://localhost/widgets/widget?name=testname&loc=20000' -H "Accept:application/json" location /widgets/widget { default_type "text/pain"; #ifisEvil... unless done inside lua content_by_lua ' ngx.say("request is:",ngx.var.request_method) ngx.say("the constant is:",ngx.HTTP_GET) --ngx.say("the type is: ", type(ngx.HTTP_GET) if ngx.var.request_method == ngx.HTTP_GET then local args = ngx.req.get_uri_args() for key, val in pairs(args) do if type(val) == "table" then ngx.say(key, ": ", table.concat(val, ", ")) else ngx.say(key, ": ", val) end end end '; } ``` The output looks like this: ``` mytestdevbox2:/var/www/nsps2# curl -i -X GET 'http://localhost/widgets/widget?name=testname&loc=20000' -H "Accept:application/json" HTTP/1.1 200 OK Server: nginx/1.6.2 Date: Wed, 25 Feb 2015 13:44:11 GMT Content-Type: text/pain Transfer-Encoding: chunked Connection: keep-alive request is:GET the constant is:2 mytestdevbox2:/var/www/nsps2# ``` The above output explains why the if statement is failing... because I'm comparing "GET" with 2. I'd rather not make up my own list of constants if they're already available and I'm just missing something here. I know there is an nginx variable called "$request_method" but I'd rather not use that because I want to keep all my logic in lua. From what I've read so far, using the "if" statement in nginx is evil! So I'm trying to stick to lua code for stuff like that. Any tips on where I might have messed up my lua code?

Original source