Correct way to select websocket upstream based on client request?

43 views
Skip to first unread message

Tran Trong Tan

unread,
Jun 13, 2024, 12:16:59 PMJun 13
to openresty-en
Hello,
I'm trying the websocket module, and lua-resty-websocket-proxy (https://github.com/Kong/lua-resty-websocket-proxy) as well.
I'm looking for a way to dynamically select an upstream based on the client body request. For example, if the request body is contain text " getProfile" then it will go to / getProfile location, another request go to /proxy location.
        location / {
            content_by_lua_block {
                server = require "resty.websocket.server"
                wb, err = server:new()
                local data, typ, err = wb:recv_frame()
                local cjson = require('cjson')
                local datajson = cjson.decode(data)
                if datajson["action"]=="getProfile" then
                    return ngx.exec("@getProfile")
                else
                    return ngx.exec("@proxy")
                end
            }
        }
        location / getProfile {
            content_by_lua_block {
                response=" getProfile response"
                local bytes, err = wb:send_text(response)
            }
        }
        location /proxy {
            content_by_lua_block {
                local proxy = require "resty.websocket.proxy"
                local wp, err = proxy.new()
                local ok, err = wp:connect("ws://127.0.0.1:9000")
                local done, err = wp:execute()
            }
        }
When I make a test request, I got a error:  "*2 lua entry thread aborted: runtime error: attempt to call ngx.exec after sending out response headers"

So I think my logic is totally wrong. Do you have any idea?

Thank you,
Tan

Junlong li

unread,
Jun 14, 2024, 5:12:27 AMJun 14
to openresty-en
Would you please change the  content_by_lua_block  to access_by_lua_block

Trần Trọng Tấn

unread,
Jun 14, 2024, 11:26:15 AMJun 14
to openre...@googlegroups.com
Hello,
I tried already but got stuck when redirect the request through the location /proxy. How can I reroute a websocket request through another location?
Should I stop using lua-resty-websocket-proxy and build myself a proxy using lua-resty-websocket module?

Thank you,
Tan

--
You received this message because you are subscribed to a topic in the Google Groups "openresty-en" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/openresty-en/Yyi_KumUJ7Y/unsubscribe.
To unsubscribe from this group and all its topics, send an email to openresty-en...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/openresty-en/5bb4195f-79f2-4f51-accd-ce734bd5d0adn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages