通过Nginx将POST数据传递到Unix域套接字

时间:2019-03-20 04:35:53

标签: nginx lua unix-socket

我有一个Unix域套接字文件,它正在与nc命令一起使用。现在,我想通过nginx访问它,但是它不起作用。我想念什么吗?

使用nc =>进行测试

$ echo  '{ "method" : "getinfo", "params" : [], "id" : "1" }' | nc -U /home/zono/.lightning/lightning-rpc
{ "jsonrpc": "2.0", "id" : "1", "result" :
{
  "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

通过nginx =>测试不起作用

// /etc/nginx/sites-enabled/default
upstream nginx-internal-sock {
  server unix:/home/zono/.lightning/lightning-rpc;
}

server {
  listen 80;
  location / {
    proxy_pass http://nginx-internal-sock;
  }
}

$ curl -H "content-type: application/json" -X POST --data '{ "method" : "getinfo", "params" : [], "id" : "1" }' http://127.0.0.1
2019-03-20T04:25:52.551Z lightningd(30143):jcon fd 32: Invalid token in json input: 'POST / HTTP/1.0??Host: nginx-internal-sock??Connection: close??C'

更新1

已经有了发展。但是我无法获取全部数据。

// install nginx-extras
apt-get install nginx-extras

// /etc/nginx/sites-enabled/default
server {
  listen 80;

  location / {
        content_by_lua '
            ngx.req.read_body()
            local body_data = ngx.req.get_body_data()

            local sock = ngx.socket.tcp()
            local ok, err = sock:connect("unix:/home/zono/.lightning/lightning-rpc")

            local bytes = sock:send(body_data)

            local line, err = sock:receive("*a")
            ngx.say(line)

            ok, err = sock:close()
        ';
  }
}

// Response is nil
$ curl -X POST --data '{ "method" : "getinfo", "params" : [], "id" : "1" }' http://127.0.0.1
nil

// /var/log/nginx/error.log
2019/03/20 07:43:39 [error] 4926#4926: *35 lua tcp socket read timed out, client: 127.0.0.1, server: , request: "POST / HTTP/1.1", host: "127.0.0.1"

// When I set "sock:receive("*l")" the response is the part of the data.
$ curl -X POST --data '{ "method" : "getinfo", "params" : [], "id" : "1" }' http://127.0.0.1
{ "jsonrpc": "2.0", "id" : "1", "result" :

我正在检查参考。 http://w3.impa.br/~diego/software/luasocket/tcp.html

  

'* a':从套接字读取,直到关闭连接。没有行尾翻译;

     

'* l':从套接字读取一行文本。该行以LF字符(ASCII 10)终止,还可以选择以CR字符(ASCII 13)开头。 CR和LF字符不包含在返回的行中。实际上,该模式会忽略所有CR字符。这是默认模式;

     

number:使方法从套接字读取指定数量的字节。

1 个答案:

答案 0 :(得分:0)

我找到了答案。

// install nginx-extras
apt-get install nginx-extras

// /etc/nginx/sites-enabled/default
server {
  listen 80;

  location / {
        content_by_lua '
            ngx.req.read_body()
            local body_data = ngx.req.get_body_data()

            local sock = ngx.socket.tcp()
            local ok, err = sock:connect("unix:/home/zono/.lightning/lightning-rpc")

            local bytes = sock:send(body_data)

            local readline = sock:receiveuntil("\\n\\n")
            local line, err, part = readline()
            if line then
                ngx.say(line)
            end

            ok, err = sock:close()
        ';
  }
}

// curl
$ curl -X POST --data '{ "method" : "getinfo", "params" : [], "id" : "1" }' http://127.0.0.1