From b31733f2333b002a0819b5d8a57473ef90338bff Mon Sep 17 00:00:00 2001 From: xfy Date: Sat, 11 Apr 2026 13:34:26 +0800 Subject: [PATCH] =?UTF-8?q?refactor(lua):=20=E7=AE=80=E5=8C=96=20ngx=20API?= =?UTF-8?q?=20=E8=A1=A8=E6=B3=A8=E5=86=8C=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 ngx 表的创建和全局设置提前,避免各 API 注册时重复检查表是否存在。 Co-Authored-By: Claude Opus 4.6 --- internal/lua/api_resp.go | 3 ++- internal/lua/coroutine.go | 17 +++++------------ 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/internal/lua/api_resp.go b/internal/lua/api_resp.go index 9534059..38f9e9d 100644 --- a/internal/lua/api_resp.go +++ b/internal/lua/api_resp.go @@ -30,9 +30,10 @@ func newNgxRespAPI(ctx *fasthttp.RequestCtx) *ngxRespAPI { // RegisterNgxRespAPI 在 Lua 状态机中注册 ngx.resp API // 这是主入口函数,由 LuaEngine 在初始化时调用 func RegisterNgxRespAPI(L *glua.LState, api *ngxRespAPI) { - // 获取已存在的 ngx 表,如果不存在则创建 + // 获取已存在的 ngx 表(必须已设置全局) ngx := L.GetGlobal("ngx") if ngx == nil || ngx.Type() != glua.LTTable { + // 如果不存在,创建新表并设置全局 ngx = L.NewTable() L.SetGlobal("ngx", ngx) } diff --git a/internal/lua/coroutine.go b/internal/lua/coroutine.go index 5fcb5b5..343d2a9 100644 --- a/internal/lua/coroutine.go +++ b/internal/lua/coroutine.go @@ -169,15 +169,11 @@ func (c *LuaCoroutine) setupSecureCoroutineLib() { // setupNgxAPI 创建 ngx API // 注册 ngx.req、ngx.resp、ngx.var、ngx.ctx、ngx.log 和 ngx.socket API func (c *LuaCoroutine) setupNgxAPI() { - // 检查是否已有 ngx 表(可能已由其他 API 注册) - existingNgx := c.Co.GetGlobal("ngx") - var ngx *glua.LTable - if existingTbl, ok := existingNgx.(*glua.LTable); ok { - ngx = existingTbl - } else { - // 创建 ngx 表 - ngx = c.Co.NewTable() - } + // 创建 ngx 表 + ngx := c.Co.NewTable() + + // 先设置到全局,让所有注册函数使用同一个 ngx 表 + c.Co.SetGlobal("ngx", ngx) // 注册 ngx.req API if c.RequestCtx != nil { @@ -203,9 +199,6 @@ func (c *LuaCoroutine) setupNgxAPI() { // 注册 ngx.socket API RegisterTCPSocketAPI(c.Co, c.Engine) - - // 将 ngx 表设置到协程环境 - c.Co.SetGlobal("ngx", ngx) } // Execute 在协程中执行 Lua 脚本(支持 Yield/Resume)