an unexpected newline appears when use memc and echo_location_async, how to delete the newline ?

agentzh agentzh at gmail.com
Sat Jun 16 02:34:35 UTC 2012


Hello!

On Sat, Jun 16, 2012 at 10:08 AM, agentzh <agentzh at gmail.com> wrote:
> Please ensure that the value you inserted into memcached does not have
> the trailing new line by using telnet to access your memcached, like
> this:
>

Sorry, I was reading too fast. For the memcached commands other than
"get", ngx_memc will return the raw memcached responses, and in your
case, for the "incr" command, the response is ended by a CR LF
sequence.

If it bothers you, then you're recommended to use ngx_lua with
lua-resty-memcached instead, for example:

  # the following line is not required if the ngx_openresty bundle is used.
  lua_package_path "/path/to/lua-resty-memcached/lib/?.lua;;";

  server {
    listen 8080;

    location ~ "^/property/([0-9]+)" {
        charset utf-8;
        default_type 'application/json';

        xss_callback_arg callback;
        xss_get on;

        content_by_lua '
            local memcached = require "resty.memcached"
            local memc = memcached:new()

            memc:set_timeout(500) -- 500 ms

            local ok, err = memc:connect("127.0.0.1", 11211)
            if not ok then
                ngx.log(ngx.ERR, "failed to connect to memcached: ", err)
                return ngx.exit(500)
            end

            local key = "property_" .. ngx.var[1]
            local newval, err = memc:incr(key, 1)
            if not newval then
                ngx.log(ngx.ERR, "failed to incr the key in memcached: ", err)
                return ngx.exit(500)
            end

            -- the connection pool capacity is set to 1024 connections
            memc:set_keepalive(0, 1024)

            ngx.print([[{"]], key, [[":"]], newval, [["}]])
        ';
    }
  }

Then we can get:

    $ curl -i localhost:8080/property/23458?callback=himycallback201203455
    HTTP/1.1 200 OK
    Server: nginx/1.0.15
    Date: Sat, 16 Jun 2012 02:31:57 GMT
    Content-Type: application/x-javascript; charset=utf-8
    Transfer-Encoding: chunked
    Connection: keep-alive

    himycallback201203455({"property_23458":"30"});

And when the callback argument is not given:

    $ curl -i localhost:8080/property/23458
    HTTP/1.1 200 OK
    Server: nginx/1.0.15
    Date: Sat, 16 Jun 2012 02:32:51 GMT
    Content-Type: application/json
    Transfer-Encoding: chunked
    Connection: keep-alive

    {"property_23458":"31"}

The example above utilizes the following components:

    http://wiki.nginx.org/HttpLuaModule
    https://github.com/agentzh/lua-resty-memcached
    https://github.com/agentzh/xss-nginx-module

If you're too lazy to download and install all these dependencies, you
can try out the ngx_openresty bundle instead:

    http://openresty.org/#Download

Best regards,
-agentzh



More information about the nginx mailing list