diff options
| author | unwox <me@unwox.com> | 2024-08-23 14:02:10 +0600 |
|---|---|---|
| committer | unwox <me@unwox.com> | 2024-08-23 14:02:10 +0600 |
| commit | 4003417f7b94648a7726995a49ab56c4bc8aad55 (patch) | |
| tree | 95fc8353e83963664c9124a2985823d7b7e13c6a /main.go | |
| parent | 37229ea3864bcdc77b2341ff12ebc55e5098718e (diff) | |
small fixes
Diffstat (limited to 'main.go')
| -rw-r--r-- | main.go | 63 |
1 files changed, 62 insertions, 1 deletions
@@ -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 () { |
