diff options
| -rw-r--r-- | lua.go | 2 | ||||
| -rw-r--r-- | main.go | 63 | ||||
| -rw-r--r-- | worker.go | 4 |
3 files changed, 65 insertions, 4 deletions
@@ -89,7 +89,7 @@ func (l *Lua) StackLen() int { return int(C.lua_gettop(l.l)) } -// ToInt converts a stack value with stack index -1 into a string. +// ToInt converts a stack value with stack index into a string. func (l *Lua) ToString(index int) string { return C.GoString(C.lua_tolstring(l.l, C.int(index), nil)) } @@ -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 () { @@ -109,7 +109,7 @@ func (w *Worker) Listen(queue chan any) { Headers: make(map[string]string), Body: "server error", } - log.Println("could not read a request body") + log.Println("could not read a request body:", err) return } w.lua.PushString(string(body)) @@ -122,7 +122,7 @@ func (w *Worker) Listen(queue chan any) { Headers: make(map[string]string), Body: "server error", } - log.Println("could not read a request body") + log.Println("could not read a request body:", err) return } |
