From 4003417f7b94648a7726995a49ab56c4bc8aad55 Mon Sep 17 00:00:00 2001 From: unwox Date: Fri, 23 Aug 2024 14:02:10 +0600 Subject: small fixes --- main.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) (limited to 'main.go') diff --git a/main.go b/main.go index 5a876b9..92ccb2f 100644 --- a/main.go +++ b/main.go @@ -3,13 +3,18 @@ package main import ( "bufio" "fmt" + "io" "log" "net/http" "os" + "strings" "time" ) + func main() { + httpClient := &http.Client{} + // queue for http messages for workers to handle msgs := make(chan interface{}, 4096) mux := http.NewServeMux() @@ -62,11 +67,67 @@ func main() { ) return 0 } + + // define luna.http module + httpModule := make(map[string]any) + httpModule["request"] = func (l *Lua) int { + body := l.ToString(-1) + url := l.ToString(-3) + method := l.ToString(-4) + l.Pop(1) + headers := make(map[string]string) + l.PushNil() + for l.Next() { + if !l.IsString(-2) || !l.IsString(-2) { + l.Pop(1) + continue + } + v := l.ToString(-1) + l.Pop(1) + // We must not pop the item key from the stack + // because otherwise C.lua_next won't work + // properly. + k := l.ToString(-1) + headers[k] = v + } + l.Pop(2) + + req, err := http.NewRequest(method, url, strings.NewReader(body)) + if err != nil { + // fixme: return error + return 0 + } + for k, v := range headers { + req.Header.Add(k, v) + } + resp, err := httpClient.Do(req) + if err != nil { + // fixme: return error + return 0 + } + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + // fixme: return error + return 0 + } + respHeaders := make(map[string]string) + for k := range resp.Header { + respHeaders[k] = resp.Header.Get(k) + } + + l.PushNumber(resp.StatusCode) + l.PushStringTable(respHeaders) + l.PushString(string(respBody)) + return 3 + } + module := make(map[string]any) module["router"] = routeModule + module["http"] = httpModule // start workers - for i := 0; i < 8; i++ { + for i := 0; i < 1; i++ { wrk := NewWorker() wrks = append(wrks, wrk) go func () { -- cgit v1.2.3