That was very helpful, thank you very much! For future reference, what I put together is:
location /set {
lua_need_request_body on;
client_max_body_size 50k;
client_body_buffer_size 50k;
content_by_lua '
text = ngx.var.request_body --couldnt directly pass to decode
json = cjson.decode(text)
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect to redis: ", err)
return
end
val = cjson.encode(json["val"]) --have to escape the json syntax
ok, err = red:set(json["key"], val)
if not ok then
ngx.say("failed to set "+json["key"]+" to "+val, err)
return
end
';
}
On Tue, Oct 9, 2012 at 6:58 PM, agentzh
<age...@gmail.com> wrote:
Hello!
On Tue, Oct 9, 2012 at 9:41 AM, Peter wrote:
> Hello,
>
> I'm diving into Nginx and I'd like to set up a very simple web service that
> allows me to send JSON via a PUT request, then pass that data to Redis.
>
> location /json2redis {
> # take JSON from PUT
> redis2_query set $key $val
> redis2_pass 127.0.0.1:6379;
> }
>
Don't use ngx_redis2 for this. Just use ngx_lua [1] + lua-resty-redis
[2] + lua-cjson [3] instead. All of these components are also included
and enabled by default in the openresty software bundle:
http://openresty.org/
> I presume I'll need something like:
>
> add_header Access-Control-Allow-Methods "PUT";
>
> but I'm not sure how to get at the passed data.
>
For cross-site AJAX? Yes, you can set response headers in your Lua
code via the ngx.header.HEADER API provided by ngx_lua:
http://wiki.nginx.org/HttpLuaModule#ngx.header.HEADER
>
> Alternately how can I pass nested brackets for a GET, along the lines of
>
> /json?key=key&val={"list":["hi":"bye"]}
>
Just use the ngx.req.get_uri_args() API provided by ngx_lua to fetch
these values in Lua:
http://wiki.nginx.org/HttpLuaModule#ngx.req.get_uri_args
and use lua-cjson [3] to decode the JSON values.
Best regards,
-agentzh
[1] http://wiki.nginx.org/HttpLuaModule
[2] https://github.com/agentzh/lua-resty-redis
[3] http://www.kyne.com.au/~mark/software/lua-cjson.php
.