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

我有一个 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

出现了新情况。但我无法获得全部数据。

// 安装 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()
        ';
  }
}

// 响应为空
$ 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"

// 当我设置 "sock:receive("*l")" 时,响应是数据的一部分。
$ 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:使方法从套接字读取指定数量的字节。

点赞
用户1582304
用户1582304

我找到了答案。

// 安装 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
2019-03-20 09:33:48