diff options
| -rw-r--r-- | lua.go | 35 | ||||
| -rw-r--r-- | main.go | 5 | ||||
| -rw-r--r-- | worker.go | 31 |
3 files changed, 57 insertions, 14 deletions
@@ -151,13 +151,36 @@ func (l *Lua) SetTableItem(key string) { C.lua_setfield(l.l, -2, C.CString(key)) } -// PushStringTable pushes string->string table onto the stack. -func (l *Lua) PushStringTable(table map[string]string) { - l.CreateTable(len(table)) - for k, v := range table { - l.PushString(v) - C.lua_setfield(l.l, -2, C.CString(k)) +// PushTable pushes string->any table onto the stack. +func (l *Lua) PushObject(table map[string]any) error { + var pushTable func(t map[string]any) error + pushTable = func (t map[string]any) error { + l.CreateTable(len(t)) + for k, v := range t { + switch v.(type) { + case string: + v, _ := v.(string) + l.PushString(v) + case func (l *Lua) int: + v, _ := v.(func (l *Lua) int) + l.PushGoFunction(v) + case int: + v, _ := v.(int) + l.PushNumber(v) + case map[string]any: + v, _ := v.(map[string]any) + pushTable(v) + default: + return fmt.Errorf( + "unsupported value type: %T", + v, + ) + } + l.SetTableItem(k) + } + return nil } + return pushTable(table) } // PushFromRef pushes a value from registry ref onto the stack. @@ -27,6 +27,7 @@ func main() { routeModule["route"] = func (l *Lua) int { fn := l.PopToRef() route := l.ToString(-1) + l.Pop(1) // find corresponding worker for the lua context var wrk *Worker for _, wrk = range wrks { @@ -111,13 +112,13 @@ func main() { // fixme: return error return 0 } - respHeaders := make(map[string]string) + respHeaders := make(map[string]any) for k := range resp.Header { respHeaders[k] = resp.Header.Get(k) } l.PushNumber(resp.StatusCode) - l.PushStringTable(respHeaders) + l.PushObject(respHeaders) l.PushString(string(respBody)) return 3 } @@ -93,14 +93,22 @@ func (w *Worker) Listen(queue chan any) { } w.lua.PushFromRef(w.routes[r.route]) - w.lua.PushString(r.request.Method) - w.lua.PushString(r.request.URL.Path) + res := make(map[string]any) + res["method"] = r.request.Method + res["path"] = r.request.URL.Path - fh := make(map[string]string) + fh := make(map[string]any) for k := range r.request.Header { fh[k] = r.request.Header.Get(k) } - w.lua.PushStringTable(fh) + res["headers"] = fh + + flatQr := make(map[string]any) + qr := r.request.URL.Query() + for k := range qr { + flatQr[k] = qr.Get(k) + } + res["query"] = flatQr body, err := io.ReadAll(r.request.Body) if err != nil { @@ -112,9 +120,20 @@ func (w *Worker) Listen(queue chan any) { log.Println("could not read a request body:", err) return } - w.lua.PushString(string(body)) + res["body"] = string(body) + + err = w.lua.PushObject(res) + if err != nil { + r.result <- &HTTPResponse { + Code: 500, + Headers: make(map[string]string), + Body: "server error", + } + log.Println("could not form a request to lua:", err) + return + } - err = w.lua.PCall(4, 3) + err = w.lua.PCall(1, 3) if err != nil { r.result <- &HTTPResponse { |
