# WebSocket 路由配置
# 需要配合 ngx_lua 模块使用

http {
    # Lua 包路径配置
    lua_package_path "/path/to/lua/?.lua;;";

    # 共享内存区域，用于 WebSocket 连接状态管理
    lua_shared_dict ws_connections 10m;
    lua_shared_dict ws_tokens 1m;

    server {
        listen 80;
        server_name example.com;

        # WebSocket 端点
        location /ws {
            # 启用 WebSocket 支持
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            # 代理头设置
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # 超时设置
            proxy_read_timeout 3600s;
            proxy_send_timeout 3600s;

            # 后端 WebSocket 服务
            proxy_pass http://127.0.0.1:8080;
        }

        # Lua 处理的 WebSocket 端点
        location /ws/lua {
            # 启用 WebSocket 支持
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            # 通过 Lua 验证连接
            access_by_lua_file /path/to/lua/ws_handler.lua;

            # 代理到后端服务
            proxy_pass http://127.0.0.1:8080;
        }

        # Token 签发端点（示例）
        location /ws/token {
            content_by_lua_block {
                local cjson = require "cjson"
                local redis = require "resty.redis"

                -- 获取连接参数
                local token = ngx.var.arg_token or ngx.md5(ngx.time() .. ngx.var.remote_addr)
                local ttl = tonumber(ngx.var.arg_ttl) or 3600

                -- 存储 Token 到共享内存
                local dict = ngx.shared.ws_tokens
                dict:set(token, "1", ttl)

                ngx.header.content_type = "application/json"
                ngx.say(cjson.encode({
                    token = token,
                    expires_in = ttl,
                    ws_url = "ws://" .. ngx.var.host .. "/ws/lua?token=" .. token
                }))
            }
        }
    }
}
