大网数据广告活动
服务器运维问答

Wrap unix sockets to make them HTTP compatible

· 52CE 我爱测

I want to use signald via web. signald is an application that provides a unix socket and communicates in JSON. I can use nginx to connect to the unix socket via HTTP(S). But signald does not understand HTTP, only pure JSON. It pr…

问题原文

原帖链接 · baumschubser · CC BY-SA 4.0

I want to use signald via web. signald is an application that provides a unix socket and communicates in JSON.

I can use nginx to connect to the unix socket via HTTP(S). But signald does not understand HTTP, only pure JSON. It produces errors like the following:

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'GET': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') at [Source: (String)"GET / HTTP/1.0"; line: 1, column: 4]

Is there a way to send JSON to my web-forwarded unix socket, just like any API that is served by a web server? I imagine something like nginx <-> http wrapper <-> unix socket.

已采纳解答

原帖链接 · baumschubser · CC BY-SA 4.0

It took some time, but I found a solution. Basically, you have to use Lua to get the request body, send it to a unix socket, read the line and send it back as server response. Use nginx with lua like this:

First install nginx-extras

Load modules ndk_http_module and ngx_http_lua_module (in this order) in nginx.conf like this:

load_module modules/ndk_http_module.so;
load_module modules/ngx_http_lua_module.so;

This is the location block for your lua-enhanced connection to the unix socket. It will send the request data to the unix socket and read by using tcpsocket:receive(). It will say() the line as response.

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

            local sock = ngx.socket.tcp()
            local ok, err = sock:connect("unix:/var/run/signald/signald.sock")

            local bytes = sock:send(body_data)

            local line, err, part = sock:receive()
            if line then
                ngx.say(line)
            end

            ok, err = sock:close()
        }
    }

Test it with a curl call like this (you don't have to care about Content-Type or method):

curl -d '{"type":"version"}' https://example.com:1234

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-11-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。